1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
#include <iostream>
#include <type_traits>
using namespace std;
template <class T,class U>
class Pair{
public:
T first;
U second;
Pair(){}
Pair(T first,T second)
:first(first),second(second)
{}
Pair(const Pair<T,U> &other){
if(is_pointer<T>::value){
first = new T(other.first);
}
else{
first = other.first;
}
if(is_pointer<U>::value){
second = new U(other.second);
}
second = other.second;
}
Pair(const Pair<T,U> &&other){
if(is_pointer<T>::value){
cout << "first is a pointer" << endl;
first = other.first;
other.first = nullptr;
}else{
first = other.first;
}
if(is_pointer<U>::value){
cout << "second is a pointer" << endl;
second = other.second;
other.second = nullptr;
}else{
second = other.second;
}
}
Pair<T,U>& operator=(Pair<T,U> other){
swap(*this,other);
return *this;
}
bool operator==(const Pair<T,U> other)const{
return first == other.first && second == other.second;
}
bool operator!=(const Pair<T,U> other)const{
return first != other.first && second != other.second;
}
bool operator<(const Pair<T,U> other)const{
return first < other.first && second < other.second;
}
bool operator>(const Pair<T,U> other)const{
return first > other.first && second > other.second;
}
void swap(Pair& a,Pair& b){
using std::swap;
swap(a.first,b.first);
swap(a.second,b.second);
}
};
int main()
{
pair<int,string> a(1,"a");
pair<int,string> b;
pair<int,string> c = pair<int,string>(3,"c");
// above line calls move cons,but lets say if instead of string we had a pointer to a string so U would be
// second in the pair,how can we check for a pointer so we can leave the pointer in a valid state in the move cons??
b = a;
if(a == b){
cout << "both pairs seem to be the same" << endl;
}
string adam = "adam";
string steve = "steve";
pair<int,string*> p_a(26,&adam);
pair<int,string*> p_b = pair<int,string*>(25,&steve);
pair<int,string*> p_c;
p_c = p_b;
cout << p_b.second << endl;
cout << p_c.second << endl;
if(p_b == p_c){
cout << "YES!" << endl;
}else{
cout << "NO!!!!" << endl;
}
}
| |