2017-06-04 19 views
-5

我有以下代码:错误:“X”不姓模板功能的X型

#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); 
} 

但是,它并不能编译,而是我收到以下错误信息:

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’

以下行出现:

cout<<"binary "<< binary<int,int>(2,7); 

为什么X名称的类型unary,但不是binary

+1

而对于'binary'功能,什么是'X'?该功能不是模板。 –

+1

您需要在本网站上阅读[*本网页以了解正确的询问方式*](https://stackoverflow.com/help/asking)。 – Shadi

回答

2

模板中的'T'只是用于函数,类或与其关联的实体的类型的占位符。并且模板参数的范围以该实体的范围结束。

See here: When does a template end?

你必须写另一个模板binary(X x, X y)如下:

template< typename X> 
X unary(X x) 
{ 
    return x*10; 
} 

template< typename X> 
X binary(X x,X y) 
{ 
    return x+y; 
} 
+0

非常感谢..它的工作 –