csguy
csguy

Reputation: 1474

Class Template with <T> or without (C++)

According to Why isn't argument deduction allowed in function return type?

When specifying a return type in a template class member function we have to be specific, for example: "the type std::vector isn't a type, std::vector<int> is."

So why do both of these examples compile? If I don't include the <T> in the first example, it shouldn't even be considered a type right?

template<typename T>
Queue<T>::Queue(const Queue& st) {}

template<typename T>
Queue<T>::Queue(const Queue<T>& st) {}

Given this template class

template<typename T>
class Queue {
   private:

    struct Node {
        Node (T value) : value(value), next(nullptr) {}
        Node (T value, Node* next) : value(value), next(next) {}
        T value;
        Node* next;
    };

    Node* head;
    size_t sz;
    void cleanList();

  public:
    Queue();

    Queue(const Queue& st);
    Queue& operator=(const Queue& st);

    ~Queue();

    size_t size() const noexcept;
    bool isEmpty() const noexcept;

    T& front();
    const Tt& front() const;

    void enqueue(const T& elem);

    void dequeue();
};

Upvotes: 6

Views: 434

Answers (1)

NathanOliver
NathanOliver

Reputation: 180640

The reason these examples work is because of the injected class name. When you have

template<typename T>
some_type<T> some_type<T>::some_func(some_type)

the return type is not in scope of the class so you need to provide the template parameter. In the function parameter you are in the scope of the class and in the scope of the class some_type is injected as a name for some_type<T> so you don't need to use some_type<T>.

Upvotes: 8

Related Questions