开发者

C++ method name as template parameter

开发者 https://www.devze.com 2023-04-08 17:49 出处:网络
How do I make the method name (here some_method) a template parameter? template<typename T> void sv_set_helper(T& d, bpn::array const& v) {

How do I make the method name (here some_method) a template parameter?

template<typename T>
void sv_set_helper(T& d, bpn::array const& v) {
  t开发者_如何学Goo_sv(v, d.some_method());
}


There is no such thing as a 'template identifier parameter', so you can't pass names as parameters. You could however take a member function pointer as argument:

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

that's assuming the function has a void return type. And you will call it like this:

sv_set_helper< SomeT, &SomeT::some_method >( someT, v );


Here is a simple example...

#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...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号