模板类的模板函数指针- c++

Template function pointer of template class - C++

本文关键字:c++ 指针 函数      更新时间:2023-10-16
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(); 

这是通过为成员函数提供专门的模板,然后简单地导出该成员函数的类部分来实现的。