Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c++ - error: ‘X’ does not name a type X in template functions

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The 'T' in the template is just a placeholder for the type used in the function, the class or the entity it is associated with. And the scope of the template parameter ends with the scope of this entity.

See here: When does a template end?

You have to write another template for binary(X x, X y) as follows:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...