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

标签 c++ templates visual-c++ stl metaprogramming

我正在努力寻找以下代码无法编译的充分理由。 它给了我以下错误。

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

我需要了解一下为什么 C++ 不允许我在函数声明中使用模板参数,因为我使用 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);
}

最佳答案

您只需要“typename”关键字。由于您的 print 函数是用 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);
}

关于c++ - 不能在函数声明中使用模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7547068/

相关文章:

c++ - 在没有 va_* 的情况下使用省略号是否可以接受?

c++ - SNAP C++ 字符串类型问题 std::string 到 TStr

c++ - 如何从仿函数访问 device_vector

c++ - 为什么建源后没有.dll文件?

c++ - 如何在使用 JNI 的 C++/Java 项目中使用 CRT 中的工具检测内存泄漏?

c++ - C++ 中的自定义迭代器

class - 当必需的属性是有条件的且值仍为空时,Angular2 将 ng-valid 类应用于字段

c# - 了解 WPF 控件样式和模板

c++ - 模板类运算符 "unresolved externals"

c++ - 如何在 VC++ 2005 中使用 OpenProcessToken、AdjustTokenPrivileges 和 GetExitCodeProcess