For templates I have seen both declarations:
template < typename T > template < class T >
What's the difference?
And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)?
template < template < typename, typename > class Container, typename Type > class Example { Container< Type, std::allocator < Type > > baz; };
There is no semantic difference between class and typename in a template-parameter. typename however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type.
C++ adds two new keywords to support templates: 'template' and 'typename'. The second keyword can always be replaced by keyword 'class'.
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
There is no difference. typename and class are interchangeable in the declaration of a type template parameter.
typename
and class
are interchangeable in the basic case of specifying a template:
template<class T> class Foo { };
and
template<typename T> class Foo { };
are equivalent.
Having said that, there are specific cases where there is a difference between typename
and class
.
The first one is in the case of dependent types. typename
is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef
in this example:
template<typename param_t> class Foo { typedef typename param_t::baz sub_t; };
The second one you actually show in your question, though you might not realize it:
template < template < typename, typename > class Container, typename Type >
When specifying a template template, the class
keyword MUST be used as above -- it is not interchangeable with typename
in this case (note: since C++17 both keywords are allowed in this case).
You also must use class
when explicitly instantiating a template:
template class Foo<int>;
I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.
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