Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not use template argument in function declaration

I'm struggling to find a good reason why the following code does not compile. It gives me the following error.

Error 2 error C2923: 'std::pair' : 'std::set::iterator' is not a valid template type argument for parameter '_Ty1'

I need a little insight, as to why C++ does not allow me to use the template parameter in the function declaration, because it I use set< int >::iterator instead of set< T >::iterator the program works.

#include<iostream>
#include<set>
using namespace std;

template <typename T>
void print(const pair< set<T>::iterator, bool> &p) //<- Here is the problem
{
    cout<<"Pair "<<*(p.first)<<" "<<p.second<<"\n";
}

int main() {
   set<int> setOfInts;
   setOfInts.insert(10);    
   pair<set<int>::iterator, bool  > p = setOfInts.insert(30);
}
like image 572
user852689 Avatar asked Sep 25 '11 17:09

user852689


2 Answers

All you need is the "typename" keyword. Since your print function is templatized with T, you have to tell the compiler the set::iterator is not a value but a type. This is how.

#include<iostream>
#include<set>
#include <utility>
using namespace std;

template <typename T>
void print(const pair< typename set<T>::iterator, bool> &p) //<- Here is the problem
{
    cout<<"Pair "<<*(p.first)<<" "<<p.second<<"\n";
}

int main() {
   set<int> setOfInts;
   setOfInts.insert(10);    
   pair<set<int>::iterator, bool  > p = setOfInts.insert(30);
}
like image 125
Benoît Avatar answered Sep 21 '22 15:09

Benoît


It seems you need the typename keyword before set<T>::iterator. This is because the compiler doesn't know that set<T>::iterator is a type, as set<T> is not a specific instantiation. set<T>::iterator could be anything and the compiler assumes it's a static member by default. So you need typename set<T>::iterator to tell him that iterator is a type. You don't need this for set<int> because that is a specific instantiation and the compiler knows about all its members.

like image 30
Christian Rau Avatar answered Sep 25 '22 15:09

Christian Rau