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

Given:

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

Why / how is C allowed to declare variables and functions of type C instead of requiring the name C<T> ? I really did not think about this before working on a template with many parameters that would make it difficult to formulate a "self type" type.

Are there any quirks I should know about?

+6
source share
3 answers

[n3290: 14.6.1/1]: Like regular (non-template) classes, the class Templates have the class name entered (section 9) . the name of the entered class can be used as a template name or type name. When used with a list-argument-template, as an argument-template for a template-template-template, or as a final identifier in a specified class type specifier of a friend's template declaration, it refers to the class template itself. Otherwise, it is equivalent to the name of the template, followed by the template parameters of the class template enclosed in <> .

Allegedly, this is just a convenient feature.

+6
source

It is just syntactic sugar.

It’s convenient not to change the signatures of your methods if you need to change the template parameters.

+2
source

Why / how is C allowed to declare variables and functions of type C instead of having to specify C?

It is just so defined. The name of the template is entered into its body and means the actual type (with arguments).

Are there any quirks I should know about?

Nothing serious. You just need to remember that this does not work for base classes, so to do CRTP you need to do

 template <class T> class A : public Base<A<T> > // not Base<A> 
+2
source

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


All Articles