【发布时间】:2017-11-08 03:42:36
【问题描述】:
我试图将函数指针作为另一个函数的参数传递,但函数指针本身可能有也可能没有参数(使其与我搜索的其他问题不同)。
代码按原样工作,但我的问题是我试图使用单个函数并传递每个不同的函数指针,但我下面有 3 个不同的函数来传递每个函数指针。我想摆脱 3 个不同的函数定义,因为除了传入的函数指针(基本上,3 个 execute_func() 定义的副本)之外,它们都是相同的。这是我到目前为止所拥有的,但这似乎不对我应该需要三个 execute_func() 调用。
class A { ... };
class B { ... };
class Test {
private:
std::function<void()> fp;
std::function<void(MyA &)> fp;
std::function<void(MyB &)> fp;
// ...
};
// Here I create a function pointer for each of my calls.
Test::Test() {
fp = std::bind(&Test::do_this, this);
fp_a = std::bind(&Test::do_a, this, std::placeholders::_1);
fp_b = std::bind(&Test::do_b, this, std::placeholders::_1);
}
// Here my intention was to have only 1 execute_func() call and I would
// pass in the pointer to the function that I want to call.
Test::test_it()
{
A a;
B b;
execute_func(fp);
execute_func(fp_a, a);
execute_func(fp_b, b);
}
// I was hoping to only need one function, but so far
// have needed 3 functions with diff signatures to make it work.
bool Test::execute_func(std::function<void()> fp) {
// ... more code here before the fp call
fp();
// ... them more common code here.
}
bool Test::execute_func(std::function<void(MyA &)> fp, MyA &a) {
// ... more common code here
fp(a);
// ... and more common code here
}
bool Test::execute_func(std::function<void(MyB &)> fp, MyB &b) {
// ... more common code here
fp(b);
// ... and more common code here.
}
// And of course the execute_func() calls call these members as passed in.
bool Test::do_this() { ... }
bool Test::do_a(MyA &a) { ... }
bool Test::do_b(MyB &b) { ... }
想到我哪里出错了?
【问题讨论】:
-
您的
do_*函数的返回类型与您传递的std::function不匹配execute_func。将来,请告诉我们您显示的代码存在什么问题。如果存在构建错误,则包括它们。 -
你知道完美转发吗?
-
我已经编辑了请求的信息,希望这更清楚一点。没有构建错误。我只是觉得我做错了,因为我不应该需要 3 个 execute_func() 调用。
-
你为什么需要
execute_func?你可以做fp(); fp_a(a); fp_b(b);。 -
您有三个数据成员(不是成员函数)
fp的声明,它们都具有不同的类型。这行不通。请创建一个minimal reproducible example 并将其与所有实际编译错误一起发布。
标签: c++ c++11 c++14 function-pointers