将指向任何成员函数的指针作为类模板参数传递 [英] Passing pointer to any member function as class template argument
本文介绍了将指向任何成员函数的指针作为类模板参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
template<typename T, typename M, M Method>
class ProxyObject
{
public:
template<typename... Args>
void Invoke (T& Object, _In_ Args&&... A)
{
(void)(Object.*Method)(std::forward<Args>(A)...);
}
};
class Object
{
public:
int MyMethod (int Val)
{
wcout << L"Hello!" << endl;
return Val;
}
};
int wmain ()
{
Object myObj;
ProxyObject<Object, decltype(&Object::MyMethod), &Object::MyMethod> obj;
obj.Invoke(myObj, 10);
return 0;
}
decltype(&Object::MyMethod)
在 obj
的定义中似乎是多余的.有什么办法可以让 ProxyObject
自动推断传递的成员函数指针的类型,这样我就可以定义 obj
如下:
The decltype(&Object::MyMethod)
seems redundant in the definition of obj
. Is there any way to make the ProxyObject
automatically infer the type of the pointer-to-member-function being passed, so that I can define obj
as follows:
ProxyObject<Object, &Object::MyMethod> obj;
推荐答案
我认为类模板是不可能的,因为你必须明确指定成员函数类型.
I think it's impossible for class template, because you have to specify the member function type explicitly.
模板函数可以帮助您进行参数推导:
Template function could help you lot with the argument deduction:
template<typename T, typename M, typename... Args>
void invoke (T& Object, M Method, Args&&... A)
{
(void)(Object.*Method)(std::forward<Args>(A)...);
}
然后
invoke(myObj, &Object::MyMethod, 10);
这篇关于将指向任何成员函数的指针作为类模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文