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

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, in the case of template template parameters, use of class instead of typename is required. See user1428839's answer below. (But this particular case is not a matter of preference, it is a requirement of the language.) (Also this will change with c++17 )


    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.


    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.


    As an addition to all above posts, the use of the class keyword is forced ( edit: up to and including C++14 ) when dealing with template template parameters, eg:

    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'
    

    see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4051.html for the acceptance of typename in template template on C++14.

    链接地址: http://www.djcxy.com/p/6332.html

    上一篇: 打印C ++ STL容器

    下一篇: 使用'class'或'typename'作为模板参数?