我正在尝试将一个函数指针 传递给另一个函数,它有一个字符串数组作为参数。到目前为止,我有以下内容:
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 传递给另一个函数:
-
制作
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; }
使用函数指针
如果函数指针不可避免,则需要两个参数
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/