Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typename / class needed when declaring template

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;
}
like image 611
NoSenseEtAl Avatar asked Jan 29 '13 18:01

NoSenseEtAl


People also ask

Should I use typename or class for template?

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>

What is the difference between typename and class in templates?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.

What is typename in template?

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.

Where and why do I have to put the template and typename keywords?

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.


1 Answers

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.

like image 97
Mike Seymour Avatar answered Oct 08 '22 23:10

Mike Seymour