C ++ Template Template Syntax

In my class, we learn C ++ 98 , so I am trying to find the correct syntax.

How to write a declaration:

template <class T>
class A{
public:
    A();
    A(const A &rhs);
    A &operator=(const A &rhs);
};

Or it should be like this:

template <class T>
class A{
public:
    A();
    A(const A<T> &rhs);
    A &operator=(const A<T> &rhs);
};

I assume that the implementation is the same for both of them.

Are they different from each other?

+4
source share
2 answers

Considering

template <class T> class A { ... };

Names A<T>and Aare valid names for designation A<T>in the scope of the class. Most prefer to use a simpler form A, but you can use A<T>.

+8
source

R Sahu , , , A A<T>, , 1 .

, , , .

"/":

#include <iostream>

// Has overloads for same class, different template order
template <class Key, class Value>
struct KV_Pair {
    Key     key;
    Value   value;

    // Correct order
    KV_Pair(Key key, Value value) :
        key(key),
        value(value) {}

    // Automatically correcting to correct order
    KV_Pair(Value value, Key key) :
        key(key),
        value(value) {}

    // Copy constructor from class with right template order
    KV_Pair(KV_Pair<Value, Key>& vk_pair) :
        key(vk_pair.value),
        value(vk_pair.key) {}

    // Copy constructor from class with "wrong" template order
    KV_Pair(KV_Pair<Key, Value>& vk_pair) :
        key(vk_pair.key),
        value(vk_pair.value) {}
};

template <class Key, class Value>
std::ostream& operator<<(std::ostream& lhs, KV_Pair<Key, Value>& rhs) {
    lhs << rhs.key << ' ' << rhs.value;
    return lhs;
}

int main() {
    // Original order
    KV_Pair<int, double> kv_pair(1, 3.14);

    std::cout << kv_pair << std::endl;

    //  Automatically type matches for the reversed order
    KV_Pair<double, int> reversed_order_pair(kv_pair);

    std::cout << reversed_order_pair << std::endl;
}

Coliru.

+2

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


All Articles