C++ method name as template parameter

前端 未结 2 1504
醉酒成梦
醉酒成梦 2020-12-24 13:52

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

template
void sv_set_helper(T& d, bpn::array const&         


        
相关标签:
2条回答
  • 2020-12-24 14:47

    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 讨论(0)
  • 2020-12-24 14:48

    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 );
    
    0 讨论(0)
提交回复
热议问题