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;
};
This piece of snippet is from c++ primer book. Although I am sure this is wrong.
Each type parameter must be preceded by the keyword class or typename:
These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:
It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively
typename
andclass
are interchangeable in the basic case of specifying a template:and
are equivalent.
Having said that, there are specific cases where there is a difference between
typename
andclass
.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 thetypedef
in this example:The second one you actually show in your question, though you might not realize it:
When specifying a template template, the
class
keyword MUST be used as above -- it is not interchangeable withtypename
in this case (note: since C++17 both keywords are allowed in this case).You also must use
class
when explicitly instantiating a template: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.
While there is no technical difference, I have seen the two used to denote slightly different things.
For a template that should accept any type as T, including built-ins (such as an array )
For a template that will only work where T is a real class.
But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers
Container
is itself a template with two type parameters.For naming template parameters,
typename
andclass
are equivalent. §14.1.2:typename
however is possible in another context when using templates - to hint at the compiler that you are referring to a dependent type. §14.6.2:Example:
Without
typename
the compiler can't tell in general whether you are referring to a type or not.