Search code examples
c++c++11variadic-templates

Passing method with variadic arguments as template parameter for a function


Suppose to have the following definitions

struct Cla {
  void w(int x){}
};

template <typename C, void (C::*m)(int)> void callm(C *c, int args) {}


template <typename C, typename... A, void (C::*m)(A...)>
void callmv(C *c, A &&...args) {}

int main(){
  callm<Cla, &Cla::w>(&cla, 3);
  callmv<Cla, int, &Cla::w>(&cla, 3);
}

The first function (callm) is ok. The second (callmv), however, does not compile, and g++ gives the following error message

test.cpp: In function ‘int main()’:
test.cpp:84:28: error: no matching function for call to ‘callmv<Cla, int, &Cla::w>(Cla*, int)’
   84 |   callmv<Cla, int, &Cla::w>(&cla, 3);
      |   ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
test.cpp:52:6: note: candidate: ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’
   52 | void callmv(C *c, A &&...args) {}
      |      ^~~~~~
test.cpp:52:6: note:   template argument deduction/substitution failed:
test.cpp:84:28: error: type/value mismatch at argument 2 in template parameter list for ‘template<class C, class ... A, void (C::* m)(A ...)> void callmv(C*, A&& ...)’
   84 |   callmv<Cla, int, &Cla::w>(&cla, 3);
      |   ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
test.cpp:84:28: note:   expected a type, got ‘&Cla::w’

What is the correct syntax? (I already checked Methods as variadic template arguments )


Solution

  • All parameters after a variadic parameter pack are always deduced and can never be passed explicitly. &Cla::w is being interpreted as the next type argument in the parameter pack A, not the non-type template argument. The error you get is the compiler complaining about &Cla::w not being a type.

    Which means you have to pass the member function first

    template <typename M, M m, typename C, typename... A>
    void callmv(C* c, A&&... args) {}
    
    callmv<decltype(&Cla::w), &Cla::w>(&cla, 3);
    

    Alternatively, you can wrap the member function

    template<typename F, typename... Args>
    void callf(F f, Args&&... args)
    {
        f(std::forward<Args>(args)...);
    }
    
    callf([](Cla* c, int i) { c->w(i); }, &c, 42);