Gas*_*sim 4 c++ function-pointers parameter-passing c++11
如何通过函数传递成员函数指针std::function.我将通过比较(实时测试)来解释它:
template<class R, class... FArgs, class... Args>
void easy_bind(std::function<R(FArgs...)> f, Args&&... args){
}
int main() {
fx::easy_bind(&Class::test_function, new Class);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息:
no matching function for call to ‘easy_bind(void (Class::*)(int, float, std::string), Class*)’
Run Code Online (Sandbox Code Playgroud)
我只是不明白为什么函数指针std::function在通过函数参数传递时无法传递给它.我该如何通过该功能?我愿意将easy_bind函数参数更改std::function为函数指针,但我真的不知道如何.
编辑:问题简化.
编辑:感谢@remyabel,我得到了我需要的东西:http://ideone.com/FtkVBg
template <typename R, typename T, typename... FArgs, typename... Args>
auto easy_bind(R (T::*mf)(FArgs...), Args&&... args)
-> decltype(fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...)) {
return fx::easy_bind(std::function<R(T*,FArgs...)>(mf), args...);
}
Run Code Online (Sandbox Code Playgroud)
ACB*_*ACB 17
http://en.cppreference.com/w/cpp/utility/functional/mem_fn是您应该使用的
struct Mem
{
void MemFn() {}
};
std::function<void(Mem*)> m = std::mem_fn(&Mem::MemFn);
Run Code Online (Sandbox Code Playgroud)
小智 3
我认为问题可以缩小到:
template<class R, class... FArgs>
void test(std::function<R(FArgs...)> f)
{
}
int main() {
test(&SomeStruct::function);
}
Run Code Online (Sandbox Code Playgroud)
错误消息非常相似,没有其他内容easy_bind:
main.cpp: In function 'int main()':
main.cpp:63:31: error: no matching function for call to
'test(void (SomeStruct::*)(int, float, std::string))'
test(&SomeStruct::function);
main.cpp:63:31: note: candidate is:
main.cpp:49:10: note: template<class R, class ... FArgs>
void test(std::function<_Res(_ArgTypes ...)>)
void test(std::function<R(FArgs...)> f)
^
main.cpp:49:10: note: template argument deduction/substitution failed:
main.cpp:63:31: note: 'void (SomeStruct::*)(int, float, std::string)
{aka void (SomeStruct::*)(int, float, std::basic_string<char>)}'
is not derived from 'std::function<_Res(_ArgTypes ...)>'
test(&SomeStruct::function);
Run Code Online (Sandbox Code Playgroud)
从本质上讲,它无法神奇地std::function为您创建一个。你需要一些类似于你的Functor别名的东西。
因此,感谢通用成员函数指针作为模板参数中提供的答案,您可以执行以下操作:
//Test Case:
struct SomeStruct {
public:
int function(int x, float y, std::string str) {
std::cout << x << " " << y << " " << str << std::endl;
return 42;
}
};
template <typename Ret, typename Struct, typename ...Args>
std::function<Ret (Struct*,Args...)> proxycall(Ret (Struct::*mf)(Args...))
{
return std::function<Ret (Struct*,Args...)>(mf);
}
int main() {
auto func3 = fx::easy_bind(proxycall(&SomeStruct::function), new SomeStruct);
int ret = func3(5, 2.5, "Test3");
std::cout << ret << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在它会自动工作。