c++ – What's the difference between typename and class in template parameters?

Question:

I don't quite understand the difference between:

template <typename T>

and

template <class T>

If it is, then what is it?

Answer:

In modern, i.e. In C ++ 17, there is no difference between class and typename when it typename to templates. However, in earlier standards, the difference was noticeable when using templated template (sic!) Parameters, i.e. when the template type is used as a template argument. In this case, using typename in front of a template type name was not valid.

An example of a templated function f (only one line needs to be uncommented):

//template<template<typename> class C>    // любой с++ 
//template<template<class>    class C>    // любой с++ 
//template<template<class>    typename C> // начиная с c++17
//template<template<typename> typename C> // начиная с c++17
void f() { }

If a modern compiler is instructed to use an older version of the standard, we can get a message like this:

template template parameter using 'typename' is a C ++ 17 extension [-Wc ++ 17-extensions]

The mentioned limitation arose due to the following syntax definition when using template template parameters before c ++ 17 (in particular in C ++ 11 p.14.1 / 1):

template < template-parameter-list > class ...opt identifieropt
template < template-parameter-list > class identifieropt = id-expression

Here you can see the explicit mention of the word class .

In c ++ 17 (draft N4687 p.17.1 / 1):

template < template-parameter-list > type-parameter-key ...opt identifieropt
template < template-parameter-list > type-parameter-key identifieropt = id-expression

the explicit class replaced with type-parameter-key , which is expanded as follows in the text:

type-parameter-key : 
    class 
    typename

In this way, typename can be used in conjunction with class .

Scroll to Top