If "struct" and "class" are same thing then why only "class" is used in template<class T> not the "struct"?

Viewed 83
template<class T>
struct E{};     //// no error


template<struct T>
struct F{};    ////error

error: a non-type template parameter cannot have type 'struct T' template

If class and struct are the same things except the by-default private and public access specifiers, then why doesn't this work ?

1 Answers

The reason is that struct and class are distinct keywords. I.e., they are not mere aliases of each other at a lexical level, but can be used differently by the language in different places. So the fact that they behave similarly in one context does not mean you can use them interchangeably in another context.

As you state, they are similar when defining a class, but that is all. Defining a type template parameter is a completely different thing than defining a class, and it has its own syntax. That syntax is unrelated to the syntax for defining a class, and the fact that the keyword class is used in both can be considered a mere coincidence from a syntactic standpoint (a helpful coincidence, but still). And that syntax dictates that class (or typename) must be used when defining a type template parameter.

Related