[英]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.第一个 function (callm) 就可以了。 The second (callmv), however, does not compile, and g++ gives the following error message
然而,第二个(callmv)没有编译,g++给出了以下错误信息
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 )
(我已经将方法检查为可变参数模板 arguments )
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. &Cla::w
被解释为参数包A
中的下一个类型参数,而不是非类型模板参数。 The error you get is the compiler complaining about &Cla::w
not being a type.你得到的错误是编译器抱怨
&Cla::w
不是一个类型。
Which means you have to pass the member function first这意味着你必须先通过会员 function
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或者,您可以包装成员 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.