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

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

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

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

我想它需要 Actor ,但如果可能的话,我更希望清洁工来做这件事。

最佳答案

would prefer a cleaner was of doing it if possible.

从这里开始

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

绑定(bind)参数(字符串数组)之后,您似乎想将可调用的东西(pass_function)传递给另一个函数(takes_a_function)。如果是这样,您在 C++ 中有更好的选择。

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

  1. 使用 lambdastd::bind

    制作takes_a_function作为模板函数,然后 与参数绑定(bind)传递可调用对象(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;
    }
    

关于c++ - 使用函数指针将字符串数组作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53416573/

相关文章:

C++智能指针混淆

javascript - jQuery id 不产生文本表示

C++:将 this 指针传递给另一个类

c++ - g++ 中的递归 lock() 调用

c++ - 成员函数的“this”参数的类型为 'const' ,但我的函数实际上不是 'const'

c++ - 将右值引用传递给 boost::in_place 函数

postgresql - 合并多个结果表并对结果进行最终查询

c++ - 了解带移位的右移运算符

C++ - 字符串容量模式

c++ - _findnext64 因访问冲突而崩溃