Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use X and not X<T> for templated constructor and destructor?

Tags:

c++

templates

In Professional C++ (2e page 689) it says:

Only for constructors and the destructor you should use X and not X<T>.

So:

template<typename T>
class X{
    X();                                  // X
    ~X();                                 // X
    X<T>& operator=(const X<T>& rhs);     // X<T>
};

Why should you not use X<T> for constructor and destructor declarations?

like image 323
user997112 Avatar asked Jun 29 '14 19:06

user997112


1 Answers

The quote is, quite simply, wrong.

X<T> is the actual name of the type:

[C++11: 14.2/6]: A simple-template-id that names a class template specialization is a class-name (Clause 9).

…and you can use it everywhere:

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

int main()
{
    X<int> x;
}

(live demo)

You may optionally use X as a "shorthand", whereby the template argument will be automatically appended for you (kinda):

[C++11: 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 <>.

…but it's certainly not required anywhere.

It sounds like the author is trying to enforce a style guide, but has made it insufficiently clear that it is entirely up to you.

like image 194
Lightness Races in Orbit Avatar answered Sep 29 '22 20:09

Lightness Races in Orbit