When declaring template params is typename
/ class
necessary (as in language could not work with diff syntax I suggest below) . I know template params can be integers so you would have to pick to default to int or to typename
/ class but still.
i.e. why not
template <T>
T max(T a, T b) {
return a > b ? a : b;
}
instead of
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
and
template<T, size_t n>
size_t array_size(const T (&)[n]) {
return n;
}
instead of
template<typename T, size_t n>
size_t array_size(const T (&)[n]) {
return n;
}
For normal template parameters (neither template template parameters, or nor non-type template parameters), you can use either class or typename interchangeably, so these two mean exactly the same thing to the compiler: template <class foo> template <typename foo>
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
In template definitions, typename provides a hint to the compiler that an unknown identifier is a type. In template parameter lists, it's used to specify a type parameter.
The typename keyword before a dependant name specifies that it is the name of a type. Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.
The language could certainly still work if template parameters defaulted to being types; just as C used to work when variable types defaulted to int
in the absence of a type specifier. There would be some ambiguities to overcome, for example:
typedef int T;
template <T> class C; // type, or non-type value of type `T`?
However, forcing you to be explicit allows much better diagnostics. If I forget to specify the type of a non-type parameter, then the compiler can immediately spot the mistake and tell me about it. In your world, it would assume I intended a type parameter, and carry on trying to interpret the template accordingly; probably producing confusing errors, or perhaps even successfully compiling something that does completely the wrong thing.
I can't comment on whether that's the reason for not allowing a default here (or for removing default variable types from C, or for never allowing them in C++), but it's certainly a good enough reason for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With