C ++: replacing elements of a template class of different types?

template< class T1, class T2 >
class Pair {
    T1 first;
    T2 second;
};

I am asked to write the swap () method so that the first element becomes second and the second first. I have:

Pair<T2,T1> swap() {
    return Pair<T2,T1>(second, first);
}

But this returns a new object, not a replacement, where I believe that it should be a void method that modifies its own data members. Can this be done since T1 and T2 are potentially different class types? In other words, I cannot just set temp = first, first = second, second = temp, because it will try to convert them to different types. I'm not sure why you might want to have a template object that changes the order of its types, as it seems like it might be confusing, but this seems to be what I'm being asked to do.

: ! , , , swap() .

+3
3

, T1 T2 . Pair<T1,T2> - , Pair<T2,T1>. , , .

:

template< class T1, class T2 >
Pair<T2,T1> swap(const Pair<T1,T2>& pair) {
    return Pair<T2,T1>(pair.second, pair.first);
}

( , Pair.)

, T1 T2 :

template< class T >
Pair<T,T>& swap(Pair<T,T>& pair) {
    using std::swap;
    swap(pair.first, pair.second);
    return pair;
}

, , .

- Pair, :

template< class T1, class T2 >
class Pair {
    T1 first;
    T2 second;
    template< class A1, class A2 >
    Pair(const A1& a1, const A2& a2) : first(a1), second (a2) {}
};

:

Pair<int,double> p1(42,47.11);
Pair<double,int> p2(p1.second,p1.first);

, , , :

Pair<char,float> p3(p1.second, p1.first); // narrowing! 
+7

, T1 T2 . ,

T2 temp (first);
first = T1(second);
second = temp;

( , *this Pair<T1,T2> Pair<T2,T1> void.)

+2

Since pair <T1,T2>and pair <T2,T1>are different types, you cannot use swap on it. The swap itself is also not much larger than using a temporary variable when the collapse operation is not performed (for example, in std::vector). Howeyer you can create a new type using links. Or you use pointers where copying is cheap.

    std::pair<int, float> a = std::pair <int, float> (3,3.5);
    std::pair<const float &, const int&> b = std::pair<const float &, const int&> (a.first, a.second);
+1
source

Source: https://habr.com/ru/post/1744827/


All Articles