No template argument needed for initialization of base class which is a template instance?

Viewed 63

I have a non-template class which is derived from a specific template instance. As usual, the base class must be initialized in the derived class's constructor. I discovered that it is possible to omit the specific template argument when calling the constructor: The major compilers (VC, g++, clang) accept it. That looks strange because the class template in itself is not a class name:

$ cat template-base.cpp && g++ --pedantic -o template-base template-base.cpp  && ./template-base
template <int I>
struct T
{
        T(int) {}
};

struct DT: public T<1>
{
        // Note: T<1>(42) is possible but not necessary.
        // T<2>(42) is an error ("T<2> is not a base class", which is correct).
        DT(): T(42) {}
};

int main()
{
        DT dt;
}

(There is this similar question answered by Johannes Schaub, in which also the derived class itself is a template. In that case the template argument is mandatory, even though it is equally well deductible there.)

Why can I use a template name like a class name here? T is not a class!

1 Answers

This has to do with the injected class name. When a class template is used as a base class, the language allows you to use the name of the template as if you specified the parameters since it knows what those parameters are. Doing

DT(): T(42) {}

gets expanded to

DT(): T<1>(42) {}

by the compiler for you.


The standard language that allows this can be found in [temp.local]

Related