C++11可变模版参数妙用
//参考:https://blog.csdn.net/wmy19890322/article/details/121427697
点击查看代码
//创建对象
template<typename T, typename... Args>
T* CreateInstance(Args... args)
{
return new T(std::forward<Args>(args)...);
}
//可变参数模版实现泛化的delegate
template<typename T, typename R, typename... Args>
class AggregateDelegate
{
public:
AggregateDelegate(T* t, R(T:: *pFunc)(Args...)) : m_pT(t), mpFunc(pFunc) {}
R operator()(Args&&... args)
{
return (m_pT->*mpFunc)(std::forward<Args>(args)...);
}
private:
T* m_pT;
R(T::*mpFunc)(Args...);
};
template<class T, class R, typename... Args>
AggregateDelegate<T, R, Args...> CreateDelegate(T* t, R(T:: *f)(Args...))
{
return AggregateDelegate<T, R, Args...>(t, f);
}
//测试代码
struct AAA1
{
void Fun(int i) { cout << i << endl; }
void Fun1(int i, double j) { cout << i + j << endl; }
int Fun2(int a, double b) { cout << a << "," << b << endl; return a + b; }
};
AAA1 a;
auto d = CreateDelegate(&a, &AAA1::Fun);
d(1);
auto d1 = CreateDelegate(&a, &AAA1::Fun1);
d1(1, 2);
AAA1 a2;
auto d2 = CreateDelegate(&a2, &AAA1::Fun2);
cout << d2(1, 2) << endl;