Sunny Shah
Sunny Shah

Reputation: 111

template< class Iterator > Is Iterator here predefined or any name can be used?

Consider the code:

template< class Iterator>
Iterator calc( Iterator a , Iterator b ){   
   if( *a == 'c' && a != b ) ++a ;
   return a ;
}

Is class Iterator important or can we give it any name like class T?

template< class T>
T calc( T a , T b ){
   if( *a == 'c' && a != b ) ++a ;
   return a ;
}

Are both these examples the same?

Upvotes: 1

Views: 51

Answers (1)

Barry
Barry

Reputation: 302932

The two are exactly the same, yes. The name Iterator just makes it clearer to the reader of your code what sorts of arguments calc is expecting to be passed in, whereas T isn't particularly illuminating. Either way, the name of the template parameter is just a name - it has no other meaning.


The C++ concepts proposal (which you had originally tagged your question as, but isn't strictly relevant to the question) would allow you to write something that is actually more meaningful:

template <Input_iterator T>
T calc(T a, T b) { ... }

This would affect the overload resolution on calc, such that calc(1, 2) would now not even consider this function -- rather than throwing a compile error when you do *a.

But even here, the T is just a name, nothing more.

Upvotes: 2

Related Questions