Callable对象,是任何可以调用的东西。函数指针,函数,重载了operator()的对象,lamda
#include#include #include #include struct S{ int f1(char c){ std::cout << "S::f1 called\n"; } void operator()(char c){ std::cout << "S::operator() called\n"; }};int main(){ int (S::*fptr)(char c) = &S::f1; S obj; (obj.*fptr)('a'); S* pobj = &obj; (pobj->*fptr)('a'); obj('a');}
在模板编程实践中,经常做调用转发,例如:
template< class Callable, typename ... Args>void dosomething( Callable f, Args... args){ f(args...); }void foo(char c){ std::cout << "foo called\n" ;}int main(){ dosomething(foo,'c'); //调用了 foo('c');}
但是,F(args...)只能应付普通函数,和重载operator()的对象。如果F是函数指针,就挂了。std::invoke就是一个utility类,帮助解决这个大问题的。
template< class Callable, typename ... Args>void dosomething( Callable f, Args... args){ //f(args...); //应用范围太窄, 对于成员函数指针,需要 (arg1.*f)(args...); 其中,arg1应从args中提取首个参数 std::invoke(f,args...); //ok 已经处理好一切}void foo(char c){ std::cout << "foo called\n" ;}int main(){ int (S::*fptr)(char c) = &S::f1; S obj; dosomething(fptr, obj, 'a');}
参考:
https://kelvinh.github.io/blog/2014/03/27/cpp-tutorial-pointer-to-member-function/
https://stackoverflow.com/questions/46388524/when-to-use-stdinvoke-instead-of-simply-calling-the-invokable
std::apply功能上类似std::invoke,Callable参数由tuple提供:
#include#include int add(int a,int b){ return a+b;}int main(){ std::cout << std::apply(add, std::make_pair(1, 2)) << '\n';}
另外还有一个未来的更强大的调用转发函数:std:call
参考:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0376r0.html