开发者

Can not use template argument in function declaration

开发者 https://www.devze.com 2023-04-08 20:08 出处:网络
I\'m struggling to find a good reason why the following code does not compile. It gives me the following error.

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.seco开发者_开发问答nd<<"\n";
}

int main() {
   set<int> setOfInts;
   setOfInts.insert(10);    
   pair<set<int>::iterator, bool  > p = setOfInts.insert(30);
}


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


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.


You need to tell the compiler that set<T>::iterator is a type. You do that using the typename keyword, as follows:

void print(const pair< typename set<T>::iterator, bool> &p) //<- Here is the problem
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号