使用函数指针将字符串数组作为参数传递

Pass string array as argument with function pointer

我正在尝试将 一个函数指针 传递给另一个 函数,它有一个字符串数组作为参数。到目前为止,我有以下内容:

void pass_function(string args[]) {    
    //so something with args.
}

void takes_a_function(void(*function)(string[])) {
    function;
}

int main()
{
    string s[] = { "hello", "World" };
    takes_a_function(pass_function(s));

    system("pause");    
    return 0;
}

问题似乎是参数 pass_function(s) 被转换为 void 而不是 void(*function)(sting *)

我想它需要演员表,但如果可能的话我更希望清洁工来做。

正确的语法是:

takes_a_function(pass_function);

或者:

void pass_function(std::string args[]);

void takes_a_function(void(*function)(std::string[]), std::string args[]) {
    function(args);
}

int main() {
    std::string s[] = { "hello", "World" };
    takes_a_function(pass_function, s);
}

would prefer a cleaner was of doing it if possible.

从这里开始

takes_a_function(pass_function(s));
                 ^^^^^^^^^^^^^^^^^^

看起来你想在绑定参数(字符串数组)。如果是这样,您在 C++ 中有更好的选择。

首先使用 std::vector<std::string>std::array<std::string, 2>如果大小已知)来存储字符串。其次,将callable传递给另一个函数,通过以下任一方式:

  1. 使用 lambdastd::bind

    takes_a_function设为模板函数,然后 与参数绑定传递可调用对象(pass_function 作为 lambda 函数)。

    #include <vector>     // std::vector
    #include <functional> // std::bind
    
    template<typename Callable> 
    void takes_a_function(const Callable &function) 
    {
        function(); // direckt call
    }
    
    int main()
    {
        std::vector<std::string> s{ "hello", "World" };
        auto pass_function = [](const std::vector<std::string> &args) { /*do something*/ };
    
        takes_a_function(std::bind(pass_function, s));        
        return 0;
    }
    
  2. 使用函数指针

    如果函数指针不可避免,则需要两个参数 takes_a_function,一个应该是函数指针,另一个 应该是字符串数组。

    #include <vector>     // std::vector
    
    // convenience type
    using fPtrType = void(*)(std::vector<std::string> const&);
    
    void pass_function(const std::vector<std::string> &args) { /*do something*/ };
    
    void takes_a_function(const fPtrType &function, const std::vector<std::string> &args)
    {
        function(args); // call with args
    }
    
    int main()
    {
        std::vector<std::string> s{ "hello", "World" };
        takes_a_function(pass_function, s);
        return 0;
    }