大佬教程收集整理的这篇文章主要介绍了c – std :: function就像委托模板类一样,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
template<class T> struct FastDelegate {}; template<class R,class... Args> struct FastDelegate<R (Args...)> { template <typename T> FastDelegate(T* t,R (T::*f)(Args...)) : m_t(t),m_f(f) {} R operator()(Args... p) { return (m_t->*m_f)(std::forWARD<Args>(p)...); } T* m_t; // How can I capture T as a type in this partial specialization? R (T::*m_f)(Args...); }; struct Test { int add ( int x,int y ) { return x+y; } }; int main () { int x = 5; int y = 4; Tester t; FastDelegate<int (int,int)> d (&t,&Test::calc ); int z = d(x,y); }
下面是一个实现此方法的示例.但是,请注意,使用std :: function< R(Args ...)>可能更容易.使用合适的lambda作为标准库可能会首先实现类似的方法.
#include <iostream> #include <utility> template<class T> struct FastDelegate {}; template<class R,class... Args> struct FastDelegate<R (Args...)> { struct dummy {}; template <typename T> FastDelegate(T* t,R (T::*f)(Args...)) : m_t(t),m_f(reinterpret_cast<void (dummy::*)()>(f)),m_call([](void(dummy::*d)(),void* v,Args... a){ typedef R (T::*mem)(Args...); T* t = static_cast<T*>(v); mem f = reinterpret_cast<mem>(d); return (t->*f)(std::forWARD<Args>(a)...); }) { } R operator()(Args... p) { return (this->m_call)(this->m_f,this->m_t,std::forWARD<Args>(p)...); } void* m_t; void (dummy::*m_f)(); R (*m_call)(void (dummy::*)(),void*,Args...); }; struct Tester { int add ( int x,int y ) { std::cout << "add(" << x << "," << y << ")\n"; return x+y; } }; int main () { int x = 5; int y = 4; Tester t; FastDelegate<int (int,&Tester::add); int z = d(x,y); }
以上是大佬教程为你收集整理的c – std :: function就像委托模板类一样全部内容,希望文章能够帮你解决c – std :: function就像委托模板类一样所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。