Why can't you define a pattern with structure?

Pretty straight forward:

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

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

      

Why?

+3


source to share


3 answers


class

is just a keyword indicating what T

the type is. It doesn't really mean that there T

should be a class. (for example, you can call foo<int>()

.)



The keyword was used class

because it typename

didn't exist when the template function was added. See Templates in C ++, typename and class .

+6


source


Since the template must be declared with class

or ...



template <typename T>
void foo() {}

      

+2


source


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 of a struct as a special case of a class in which all members are public. Thus, including this parameter in the list of template parameters will not be as general.

+1


source







All Articles