不能在函数声明中使用模板参数

use*_*689 5 c++ templates stl metaprogramming visual-c++

我很难找到以下代码无法编译的好理由.它给了我以下错误.

错误2错误C2923:'std :: pair':'std :: set :: iterator'不是参数'_Ty1'的有效模板类型参数

我需要一点见解,为什么C++不允许我在函数声明中使用template参数,因为我使用set <int> :: iterator而不是set <T> :: iterator程序可以工作.

#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);
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*oît 9

您只需要"typename"关键字.由于您的打印函数使用T进行模板化,因此您必须告诉编译器set :: iterator不是值而是类型.这是怎么回事.

#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);
}
Run Code Online (Sandbox Code Playgroud)