Use 'class' or 'typename' for template parameters?

Kristopher Johnson picture Kristopher Johnson · Oct 17, 2008 · Viewed 273.8k times · Source

Possible Duplicate:
C++ difference of keywords ‘typename’ and ‘class’ in templates

When defining a function template or class template in C++, one can write this:

template <class T> ...

or one can write this:

template <typename T> ...

Is there a good reason to prefer one over the other?


I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."

  • They are equivalent (except as noted below).
  • Some people have reasons to always use typename.
  • Some people have reasons to always use class.
  • Some people have reasons to use both.
  • Some people don't care which one they use.

Note, however, that before C++17 in the case of template template parameters, use of class instead of typename was required. See user1428839's answer below. (But this particular case is not a matter of preference, it was a requirement of the language.)

Answer

itsmatt picture itsmatt · Oct 17, 2008

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.