Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What feature of C++ lets template classes refer to themselves without template arguments?

Tags:

c++

templates

Given:

template <typename T>
class C {
    C & operator ++ () { ... }
};

Why/how is C allowed to declare variables and functions of type C rather than being required to name C<T>? I had not really thought about it before working on a template with many parameters that would make spelling out the "self type" inconvenient.

Are there any quirks of this I should know about?

like image 686
Ben Jackson Avatar asked Nov 07 '11 01:11

Ben Jackson


2 Answers

[n3290: 14.6.1/1]: Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used as a template-name or a type-name. When it is used with a template-argument-list, as a template-argument for a template template-parameter, or as the final identifier in the elaborated-type-specifier of a friend class template declaration, it refers to the class template itself. Otherwise, it is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>.

Ostensibly, it's merely a convenience feature.

like image 55
Lightness Races in Orbit Avatar answered Sep 19 '22 12:09

Lightness Races in Orbit


It's just syntactic sugar.

It is convenient to not have to change the signatures of your methods if you have to change the template parameters.

like image 24
Nick Strupat Avatar answered Sep 19 '22 12:09

Nick Strupat