[英]Template function pointer of template class - C++
template<typename C, typename Arg>
int foo(C* c, int (C::*func)(Arg), Arg a)
{
c->*func(a);
}
要调用“ foo”,我们必须同时输入A *和&A :: bar,
foo(A*,&A::bar,var);
有没有一种方法可以定义模板(例如,作为结构),从而无需传递“ A *”? 如何定义一个从“&A :: bar”获取A *的模板?
如果要在该实例上调用非静态方法,则无法避免传递该实例,除非您不介意在临时的,默认构造的实例上调用它:
template<typename C, typename Arg>
int call_on_temp(int (C::*func)(Arg), Arg a)
{
C temp;
temp.*func(a);
}
或调用者将实例明确绑定到函子中:
template<typename F, typename Arg>
int call_on_functor(F func, Arg a)
{
func(a);
}
这使得呼叫站点很难看:
call_on_functor(std::bind(std::mem_fn(&Class::method), instance), arg);
(并且您仍然需要该实例,您只是将其从一个地方移到了另一个地方)。
请注意,您可以从函数指针中推断出A的类型 ,只是无法推断出实例来在上调用函数 。 如果要调用静态方法,则根本不需要类类型:
template<typename Arg>
int call_on_static(int (*func)(Arg), Arg a)
{
func(a);
}
这应该做您需要做的事情:
template<typename unused>
struct member_function_pointer_type_helper;
template<typename R, typename C>
struct member_function_pointer_type_helper<R C::*> {
typedef C type;
};
template<typename F>
struct member_function_pointer_type : member_function_pointer_type_helper<typename std::remove_cv<F>::type> {
};
例:
struct A { void foo() { ... } };
typedef member_function_pointer_type<decltype(&A::foo)>::type a_type; // 'A'
a_type my_a;
my_a.foo();
通过仅为成员函数提供专门的模板,然后仅导出该成员函数的类部分,就可以实现此目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.