我希望接受模板成员函数作为模板参数。
例如,给定此类:
class A
{
public:
template<typename... Args>
void Foo(Args...) {}
void Bar() {}
};
我希望能够致电:
Invoke<&A::Foo>(5, true);
并使其类似于调用:
A a;
a.Foo(5, true);
我知道如何为
Bar()
执行此操作:template<void (A::*F)()>
void Invoke()
{
A a;
(a.*F)();
}
int main()
{
Invoke<&A::Bar>();
}
是否可以将其扩展为模板成员函数指针?或者类似地,编写这样的转发函数,该函数可以处理具有任何参数类型的函数。这不起作用,但是类似于:
template<typename... Args, void (A::*F)(Args...)>
void Invoke(Args... args)
{
A a;
(a.*F)(args...);
}
我可以理解为什么这不可能,但是如果是这样,您能指出为什么这样做的标准吗?我还试图了解有关标准细节的更多信息。
最佳答案
不需要。虽然如果您只需要Foo
的特定实例化,则可以使用Invoke<&A::Foo<int, bool>>
。
为了能够使用不同的签名,您必须修改Invoke
才能对任何类型的可调用对象进行操作。然后,您将必须定义一个调用实际函数的可调用对象:
struct callable_foo
{
explicit callable_foo( A& obj ) : _obj( obj ){}
template< typename ...Args >
void operator ()( Args&&... args )
{
_obj.Foo( std::forward< Args >( args )... );
}
A& _obj;
}