Kam*_*ran 0 c++ templates definition ambiguity std-pair
在c ++中对类的定义中有两个typedef.它们是为了什么?在代码中没有使用它们!
template <class T1, class T2> struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& x, const T2& y) : first(x), second(y) {}
template <class U, class V>
pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}
Run Code Online (Sandbox Code Playgroud)
它们只是为了您的方便,所以您可以在代码中使用它们.C++没有反射模型,所以这是你"知道"它们是什么类型的唯一方法假设你定义了自己的对
typedef对MyPair;
然后你可以使用
MyPair :: first_type
MyPair :: second_type
例如,
MyPair::first_type my_first(MyPair& pair)
{
return pair.first;
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您更改MyPair的原始定义,则无需在代码中的任何位置进行研究和替换.
它允许其他代码片段声明类型的变量,而无需直接访问类型参数(T1和T2).类似的,不那么简单的例子是容器类中的typedef:
vector<int>::iterator curNum;
for(curNum = someVect.begin(); curNum != someVect.end(); curNum++)
; //do stuff
Run Code Online (Sandbox Code Playgroud)
这使用iterator矢量模板中定义的typedef 来创建curNum.C++ 0x的auto关键字有点不太有用:
for(auto curNum = someVect.begin(); curNum != someVect.end(); curNum++)
;
Run Code Online (Sandbox Code Playgroud)