I have the following code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template< typename X>
X unary(X x)
{
return x*10;
}
X binary( X x,X y)
{
return x+y;
}
int main()
{
vector<int> v1{1,2,3,4,5,6};
vector<int> v2(v1);
vector<int>::iterator i;
for(i=v2.begin();i<v2.end();i++)
cout<<*i<<endl;
cout<<"unary "<<unary<int>(2)<<endl;
cout<<"binary "<<binary<int>(2,7);
}
However, it does not compile, and instead I get the following error message:
transform.cpp:12:1: error: ‘X’ does not name a type
X binary( X x,X y)
transform.cpp: In function ‘int main()’:
transform.cpp:28:19: error: expected primary-expression before template’
Which appears on the following line:
cout<<"binary "<< binary<int,int>(2,7);
Why does X
name a type for unary
, but not binary
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…