4

In my class, we are studying C++98 so I'm trying to find the proper syntax.

How should one write the declaration:

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

Or should it be like this:

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

I guess the implementation is the same for both of them.

Are they different from one to another?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Dannz
  • 495
  • 8
  • 20
  • Aren't there examples in your textbook? – Barmar Feb 12 '17 at 05:48
  • @Barmar Couldn't find for this specific problem. – Dannz Feb 12 '17 at 05:50
  • 1
    I see both syntaxes being used in http://stackoverflow.com/questions/7638296/how-to-write-template-class-copy-constructor and http://stackoverflow.com/questions/19167201/copy-constructor-of-template-class – Barmar Feb 12 '17 at 05:56

2 Answers2

8

Given

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

The names A<T> and A are both valid names to refer to A<T> in the scope of the class. Most prefer to use the simpler form, A, but you may use A<T>.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

While R Sahu's answer is correct, I think it's good to illustrate the case where A is not the same as A<T>, particularly where there are more than 1 instantiated template argument.

For example, when writing a copy constructor for a templated class with two template arguments, because the order of the arguments matters, you need to explicitly write out the templated types for the overloads.

Here is an example with a "Key/Value" type class:

#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;
}

See it live on Coliru.

CinchBlue
  • 6,046
  • 1
  • 27
  • 58