Use 'class' or 'typename' for template parameters?
According to Scott Myers, Effective C++ (3rd ed.) item 42 (which must, of course, be the ultimate answer) - the difference is "nothing".
Advice is to use "class" if it is expected T will always be a class, with "typename" if other types (int, char* whatever) may be expected. Consider it a usage hint.
Stan Lippman talked about this here. I thought it was interesting.
Summary: Stroustrup originally used class
to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename
to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, class
kept its overloaded meaning.
As an addition to all above posts, the use of the class
keyword is forced (up to and including C++14) when dealing with template template parameters, e.g.:
template <template <typename, typename> class Container, typename Type>
class MyContainer: public Container<Type, std::allocator<Type>>
{ /*...*/ };
In this example, typename Container
would have generated a compiler error, something like this:
error: expected 'class' before 'Container'