mardi 29 novembre 2022

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 )

Aucun commentaire:

Enregistrer un commentaire