3

Pretty straight-forward:

template <class T>
void foo() {}  //compiles

template <struct T>
void goo() {}  //doesn't

Why?

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625

3 Answers3

6

class is only a keyword to indicate that T is a type. It does not actually mean T must be a class. (e.g. you can call foo<int>().)

The class keyword was used because typename didn't exist when the template feature was added. See Templates in c++,typename and class.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
2

Because a template has to be declared with either class or...

template <typename T>
void foo() {}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • I'm looking more for the reasoning behind this specification, rather than just "because that's what the standard says". – Luchian Grigore Mar 12 '12 at 18:28
  • 1
    @LuchianGrigore: There is not much to reason about... there is a need for a keyword that identifies a placeholder for a *type*, and while defining the language they could have decided basically *anything*, for example `template `, but they chose to use `class` (reuse of an existing keyword to avoid incrementing the number of reserved keywords). Note that this use of `class` is not synonym for `class` in a type declaration, which is the use of `class` that is in turn similar to `struct`. – David Rodríguez - dribeas Mar 12 '12 at 18:31
  • @DavidRodríguez-dribeas Actually Kenny's answer provides a pretty good explanation. Even your comment provides more explanation. – Luchian Grigore Mar 12 '12 at 18:33
1

Because, the grammar forbids it:

template-declaration: 

export_opt template< template-parameter-list > declaration

template-parameter-list:
template-parameter
parameter-declaration

type-parameter:

class identifier
class identifier = type-id
typename identifier
typename identifier = type-id
template < template-parameter-list > class identifier
template < template-parameter-list > class identifier = template-name

Alternatively , you can think that struct is a special case of a class where the members are all public. Thus, allowing it in the template-parameter-list would not be as general.