HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacppCritical

What is the difference between "typename" and "class" template parameters?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typenameandclassbetweenthedifferencetemplatewhatparameters

Problem

For templates I have seen both declarations:

template 
template 


What's the difference?

And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)?

template  class Container, typename Type >
class Example
{
     Container > baz;
};

Solution

typename and class are interchangeable in the basic case of specifying a template:

template
class Foo
{
};


and

template
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
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  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;


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.

Code Snippets

template<class T>
class Foo
{
};
template<typename T>
class Foo
{
};
template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};
template < template < typename, typename > class Container, typename Type >
template class Foo<int>;

Context

Stack Overflow Q#2023977, score: 628

Revisions (0)

No revisions yet.