C++方法名称作为模板参数

Nei*_*l G 22 c++ templates

如何使方法名称(此处some_method)成为模板参数?

template<typename T>
void sv_set_helper(T& d, bpn::array const& v) {
  to_sv(v, d.some_method());
}
Run Code Online (Sandbox Code Playgroud)

Nim*_*Nim 26

这是一个简单的例子......

#include <iostream>

template<typename T, typename FType>
void bar(T& d, FType f) {
  (d.*f)(); // call member function
}


struct foible
{
  void say()
  {
    std::cout << "foible::say" << std::endl;
  }
};

int main(void)
{
  foible f;
  bar(f,  &foible::say); // types will be deduced automagically...
}
Run Code Online (Sandbox Code Playgroud)


K-b*_*llo 24

没有"模板标识符参数"这样的东西,因此您不能将名称作为参数传递.但是,您可以将成员函数指针作为参数:

template<typename T, void (T::*SomeMethod)()>
void sv_set_helper(T& d, bpn::array const& v) {
   to_sv(v, ( d.*SomeMethod )());
}
Run Code Online (Sandbox Code Playgroud)

假设函数具有void返回类型.你会这样称呼它:

sv_set_helper< SomeT, &SomeT::some_method >( someT, v );
Run Code Online (Sandbox Code Playgroud)