Difference of keywords 'typename' and 'class' in templates?

后端 未结 5 577
南方客
南方客 2020-11-22 16:37

For templates I have seen both declarations:

template < typename T >
template < class T >

What\'s the difference?

And

5条回答
  •  悲哀的现实
    2020-11-22 17:11

    This piece of snippet is from c++ primer book. Although I am sure this is wrong.

    Each type parameter must be preceded by the keyword class or typename:

    // error: must precede U with either typename or class
    template  T calc(const T&, const U&);
    

    These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:

    // ok: no distinction between typename and class in a template parameter list
    template  calc (const T&, const U&);
    

    It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively

提交回复
热议问题