【问题标题】:Pass string array as argument with function pointer使用函数指针将字符串数组作为参数传递
【发布时间】:2019-04-24 06:55:30
【问题描述】:

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

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 *)

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

【问题讨论】:

  • pass_function(s)void 类型,因为您调用了该函数。然后你尝试传递返回值。
  • 你的takes_a_function 是noop
  • 您能描述一下您在这里实际想要实现的目标吗?

标签: c++ c++11 parameter-passing function-pointers


【解决方案1】:

如果可能的话,希望清洁工这样做。

从这里

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

绑定参数(字符串数组)之后,您似乎想将可调用的东西(pass_function)传递给另一个函数(takes_a_function)。如果是这样,您在 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;
    }
    

【讨论】:

    【解决方案2】:

    正确的语法是:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 2013-01-04
      • 2020-05-01
      • 2020-11-08
      • 2012-01-24
      • 2018-05-14
      • 1970-01-01
      相关资源
      最近更新 更多