Is the following C++ code correct? And if so, could anybody point me to a paragraph in the standard that mentions this? It seems that one can use template-name instead of template-id in a scope enclosed with template and the compiler automatically adds the template argument list.
template<class Type>
class Mana {
public:
Mana(const Mana& m) {/*...*/}
Mana() {/*...*/}
};
as opposed to:
template<class Type>
class Mana {
public:
Mana(const Mana<Type>& m) {/*...*/}
Mana() {/*...*/}
};
The code compiles with g++ as well as in MS visual studio.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.
There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
Class Templates like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. Following is a simple example of a template Array class.
Yes the code is correct. (The quote: §14.6.1[temp.local]/2
Within the scope of a class template specialization or partial specialization, when the injected-class-name is used as a type-name, it is equivalent to the template-name followed by the template-arguments of the class template specialization or partial specialization enclosed in
<>
. [ Example:template<template<class> class T> class A { }; template<class T> class Y; template<> class Y<int> { Y* p; // meaning Y<int> Y<char>* q; // meaning Y<char> A<Y>* a; // meaning A<::Y> class B { template<class> friend class Y; // meaning ::Y }; };
— end example ]
)
In fact this is used all over the place in the standard as well, e.g.
// §20.4.2.1[tuple.cnstr]/10-13
tuple(const tuple& u) = default;
tuple(tuple&& u) = default;
// §21.4.6.1[string::op+=]/1-2
basic_string& operator+=(const basic_string& str);
// etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With