c – 将具有所有参数的成员函数传递给std :: function

前端之家收集整理的这篇文章主要介绍了c – 将具有所有参数的成员函数传递给std :: function前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从成员函数创建一个std ::函数,而不需要键入std :: placeholder :: _ 1,std :: placeholder :: _ 2等 – 我想“保留”所有参数,只保存对象本身.
  1. struct Foo{
  2. int bar(int,float,bool) {return 0;}
  3. };
  4. int baz(int,bool) {return 0;}
  5. int main() {
  6. Foo object;
  7. std::function<int(int,bool)> fun1 = baz; // OK
  8. std::function<int(int,bool)> fun2 = std::bind(&Foo::bar,object); // WRONG,needs placeholders
  9. }

我不想在这个阶段提供参数,我只想把功能对象存储在某个地方.例如,我想要使用具有全局函数和成员函数的std :: vector.这很容易做到FastDelegate(fastdelegate :: MakeDelegate(object,& Class :: function)).

我不想使用lambda,因为它需要我重新引用参数.我只是想要旧的FastDelegate行为.

解决方法

您可以使用函数模板,这将推导出所有成员函数参数类型,如下所示:
  1. template<typename Obj,typename Result,typename ...Args>
  2. auto make_delegate(const Obj &x,Result (Obj::*fun)(Args...)) -> // ...

并将返回特殊的委托对象,它将包含您的对象(或指向它的对象),并将所有传递的参数转发到底层对象的成员函数

  1. template<typename Obj,typename ...Args>
  2. struct Delegate
  3. {
  4. Obj x;
  5. Result (Obj::*f)(Args...);
  6.  
  7. template<typename ...Ts>
  8. Result operator()(Ts&&... args)
  9. {
  10. return (x.*f)(forward<Ts>(args)...);
  11. }
  12. };

您将获得以下使用语法:

  1. function<int(int,bool)> fun = make_delegate(object,&Foo::bar);

这里是完整的例子:

  1. #include <functional>
  2. #include <iostream>
  3. #include <utility>
  4.  
  5. using namespace std;
  6.  
  7. struct Foo
  8. {
  9. int bar(int x,float y,bool z)
  10. {
  11. cout << "bar: " << x << " " << y << " " << z << endl;
  12. return 0;
  13. }
  14. };
  15.  
  16. int baz(int x,bool z)
  17. {
  18. cout << "baz: " << x << " " << y << " " << z << endl;
  19. return 0;
  20. }
  21.  
  22. template<typename Obj,typename ...Args>
  23. struct Delegate
  24. {
  25. Obj x;
  26. Result (Obj::*f)(Args...);
  27.  
  28. template<typename ...Ts>
  29. Result operator()(Ts&&... args)
  30. {
  31. return (x.*f)(forward<Ts>(args)...);
  32. }
  33. };
  34.  
  35. template<typename Obj,Result (Obj::*fun)(Args...))
  36. -> Delegate<Obj,Result,Args...>
  37. {
  38. Delegate<Obj,Args...> result{x,fun};
  39. return result;
  40. }
  41.  
  42. int main()
  43. {
  44. Foo object;
  45. function<int(int,bool)> fun[] =
  46. {
  47. baz,make_delegate(object,&Foo::bar) // <---- usage
  48. };
  49. for(auto &x : fun)
  50. x(1,1.0,1);
  51. }

输出为:

  1. baz: 1 1 1
  2. bar: 1 1 1

Live Demo on Coliru

猜你在找的C&C++相关文章