#include <iostream>
using namespace std;
template<int x, int y>
void add()
{
cin >> x >> y;
cout << x + y << endl;
}
int main()
{
add<1,2>();
return 0;
}
在Windows10 + visual studio 2017中,它出错:二进制&gt; &GT; :STD的左操作数的运算符:: istream类型未找到(或没有可接受的转换)
参数x
和y
与其他普通int
变量有什么不同?
答案 0 :(得分:0)
我想你想要更像这样的东西:
#include <iostream>
using namespace std;
template<class T>
void add(T x, T y)
{
cin >> x >> y;
cout << x + y << endl;
}
int main()
{
add(1, 2);
return 0;
}
在您的示例中,x
和y
是模板参数,但您尝试将它们用作cin
和cout
语句中的值。
答案 1 :(得分:0)
是的,模板参数与普通功能参数不同。模板参数是编译时常量。鉴于您对add
模板的定义,当您使用add<1,2>
实例化它时,编译器实际上会创建一个这样的函数:
// where 'function_name' is a compiler generated name which is
// unique for the instantiation add<1,2>
void function_name()
{
cin >> 1 >> 2;
cout << 1 + 2 << endl;
}
显然,你不能这样做:
cin >> 1 >> 2;
您需要输入实际可修改的对象,而不是常量。