如何将具有模板参数的函数传递给其他函数?
template <class _T>
void inc(int &x) {
x++;
}
template <class FUNC>
void add(int &x, FUNC f) {
f(x);
}
int main() {
int x = 0;
add(x, inc);
return 0;
}
因此,我收到“错误:没有匹配的函数来调用'add'”。
inc
是模板,而不是函数。您需要通过inc<int>
:
template <class _T>
void inc(int &x) {
x++;
}
template <class FUNC>
void add(int &x, FUNC f) {
f(x);
}
int main() {
int x = 0;
add(x, inc<int>);
return 0;
}
(修复了f
在主函数中而不是在添加中键入错误的问题。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句