![](/img/trans.png)
[英]Template in GCC doesn't see a function declared after it, but before instantiation
[英]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;
}
我收到以下错误:
错误:变量或字段'foo'声明为空
错误:预期在“ a”之前的“)”
错误:预期在“ b”之前的“)”
在函数'int main()'中:错误:在此范围内未声明'foo'
模板中的T
和U
不是类型。 您需要将其更改为:
template<typename T, typename U>
void foo(T a, U b) {
}
模板参数可以是整数,例如:
template<int A, int B>
void bar()
{
std::cout << A+B << std::endl;
}
但是,似乎您想根据参数的类型而不是整数值对方法进行参数化。 正确的模板是这样的:
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.