mypair
#include<iostream>
#include<vector>
#include <algorithm>
#include<map>
using namespace std;
template<typename T1, typename T2, typename T3>
class mypair {
public:
T1 first;
T2 second;
T3 third;
mypair() :first(T1()), second(T2()), third(T3()) {}
mypair(const T1& a, const T2& b, const T3& c) :first(a), second(b), third(c) {}
template<typename t1, typename t2, typename t3>
friend ostream& operator<<(ostream& out, const mypair<t1, t2, t3>& rhs);
};
template<typename t1, typename t2, typename t3>
ostream& operator<<(ostream& out, const mypair<t1, t2, t3>& rhs)
{
out << rhs.first << " "<<rhs.second<<" "<<rhs.third<<endl;
return out;
}
template<typename s1, typename s2, typename s3>
inline mypair<s1, s2, s3> make_mypair(const s1& x, const s2& y, const s3& z) {
return mypair<s1, s2, s3>(x, y,z);
}
template<typename T1, typename T3> //偏特化版本处理char*,
inline mypair<T1, string, T3> make_mypair(const T1& x, const char* y, const T3& z) {
string str = y;
return mypair<T1, string, T3>(x, str, z);
}
int main()
{
int n = 10;
mypair<int, string, int> pa(0,"hello",100);
cout <<"test-pa:"<< pa;
cout << "*************map_tset*****************"<<endl;
map<int, mypair<int, string, int> > mp;
mp[0] = pa;
mp[1] = mypair<int, string, int>(1,"world",20);
mp.insert(make_pair(2, make_mypair(2,"I come",666)));
//此处字符串偏特化处理,很奇怪,vs2019不处理的话,这里的char*不会隐式转换为string
for (auto it : mp)
{
cout << it.second;
}
return 0;
}
测试结果:
pair源码
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& a, const T2& b) : first(a), second(b) {}
#ifdef __STL_MEMBER_TEMPLATES
template <class U1, class U2>
pair(const pair<U1, U2>& p) : first(p.first), second(p.second) {}
#endif
};
template <class T1, class T2>
inline bool operator==(const pair<T1, T2>& x, const pair<T1, T2>& y) {
return x.first == y.first && x.second == y.second;
}
template <class T1, class T2>
inline bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y) {
return x.first < y.first || (!(y.first < x.first) && x.second < y.second);
}
template <class T1, class T2>
inline pair<T1, T2> make_pair(const T1& x, const T2& y) {
return pair<T1, T2>(x, y);
}