[英]Template function declared as void - code doesn't work?
#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;
}
I get the following errors: 我收到以下错误:
error: variable or field 'foo' declared void
错误:变量或字段'foo'声明为空
error: expected ')' before 'a'
错误:预期在“ a”之前的“)”
error: expected ')' before 'b'
错误:预期在“ b”之前的“)”
In function 'int main()': error: 'foo' was not declared in this scope
在函数'int main()'中:错误:在此范围内未声明'foo'
Your T
and U
in your template are not types. 模板中的
T
和U
不是类型。 You need to change it to: 您需要将其更改为:
template<typename T, typename U>
void foo(T a, U b) {
}
Template parameters can be integers, for example: 模板参数可以是整数,例如:
template<int A, int B>
void bar()
{
std::cout << A+B << std::endl;
}
However, it seems like you want to parametrize your method on the types of the parameters, not on integer values . 但是,似乎您想根据参数的类型而不是整数值对方法进行参数化。 The correct template would be this:
正确的模板是这样的:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.