Is typename / class necessary when declaring a template

When declaring template parameters, typename/ is required class(as in the language it cannot work with diff syntax, which I suggest below). I know that the template options can be integers, so you will need to choose the default value for int or typename/ class, but still.

i.e. why not

template <T>
T max(T a, T b) {
    return a > b ? a : b;
}

instead

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

template<typename T, size_t n>
size_t array_size(const T (&)[n]) {
    return n;
}
+5
source share
2 answers

The language can certainly work if the default template parameters are types; just like C is used to work when the types of variables by default do not match intin 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`?

, , . , , . , , ; , , , -, .

, ( C , ++), , , .

+8

. typename , . , , typename, , .

-1

All Articles