Template function declared as void - code doesn't work?
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <string> template<int T, int U> void foo(T a, U b) { std::cout << a+b << std::endl; } int main() { foo(2,4); return 0; } |
我得到以下错误:
error: variable or field 'foo' declared void
error: expected ')' before 'a'
error: expected ')' before 'b'
In function 'int main()':
error: 'foo' was not declared in this scope
模板中的
1 2 3 | template<typename T, typename U> void foo(T a, U b) { } |
模板参数可以是整数,例如:
1 2 3 4 5 | template<int A, int B> void bar() { std::cout << A+B << std::endl; } |
但是,您似乎希望对方法的参数类型进行参数化,而不是对整数值进行参数化。正确的模板是:
1 2 3 4 5 6 7 8 9 10 11 | template<typename T, typename U> void foo(T a, U b) { std::cout << a+b << std::endl; } int main() { bar<2,4>(); foo(2,4); // note: template parameters can be deduced from the arguments return 0; } |