开发者

c++ pair template struct declaration ambiguity!

开发者 https://www.devze.com 2023-01-05 21:28 出处:网络
In definition of pair class in c++ there are two typedefs. what are they for? there are no use of them in the code!

In definition of pair class in c++ there are two typedefs. what are they for? there are no use of them in the code!

template <class T1, class T2> struc开发者_如何学Pythont 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) { }
}


They are just here for you convenience, so you can use them in your code. C++ doesn't have a reflection model , so that's the only way you have "know" what types they are Suppose you define your own pair

typedef pair MyPair;

Then you can use

MyPair::first_type
MyPair::second_type

for example,

MyPair::first_type my_first(MyPair& pair)
{
    return pair.first;
}

Then you won't need to research and replace everywhere in your code , if you change the original definition of MyPair.


It's to allow other pieces of code to declare variables of the types without having direct access to the type parameters (T1 & T2). A similar, less trivial, example are the typedefs in container classes:

vector<int>::iterator curNum;
for(curNum = someVect.begin(); curNum != someVect.end(); curNum++)
    ; //do stuff

This uses the typedef iterator defined in the vector template to create curNum. It will be somewhat less useful come C++0x's auto keyword:

for(auto curNum = someVect.begin(); curNum != someVect.end(); curNum++)
    ;


This is so you can refer to the types in your code using e.g. pair<int,string>::first_type myVariable, or if you've typedef'd a particular flavour of the template then MyPair::first_type myVariable.


They are public aliases of the passed-in T1 and T2 types that can be referenced after the object is constructed.

0

精彩评论

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