Your question is somewhat confusing. At first I thought you were asking about base<Type>
in the member initialization list, then I thought you were asking about accessing member
, then back to the first... Now I'm thinking you're asking both, so I'll answer both.
Not writing Type here gives error, why?
When you use a class template's name (my_class_templ
), it refers to the template, which is not a type. In order to use it as a type, you need to provide template parameters (my_class_templ<int>
, my_class_templ<T>
). So wherever a type name is needed (and that includes the base class names in an initialization list), you need to provide template parameters.
You can omit the template parameter list for class templates names within the class template's definition. For example, a copy constructor can be declared as
my_class_templ(const my_class_templ& rhs);
instead of
my_class_templ<T>(const my_class_templ<T>& rhs);
This is just a little syntactic sugar, allowing your to type less.
However, outside of the class templates definition, you need to explicitly spell out all the template parameters. This is also true for derived classes:
my_dervied_class_templ(const my_derived_class_templ& rhs)
: my_class_templ<T>(rhs) // need to spell out <T> here
{
}
I get error 'member' was not declared in this scope
. How to fix the problems?
When your template is encountered first by the compiler, there's only its definition and no instantiations have been seen by the compiler yet. The compiler doesn't know whether, at a point of instantiation, there might be specializations of the template in scope or not. However, you could specialize your template for Base<T>::member
to refer to something else or not to be defined entirely. (Say, a specialization Base<void>
doesn't have a data member.) Therefore, the compiler must not speculate about the members of Base
. Consequentially, they will not be looked up in Derived
.
The result of this is that, if you need to refer to one of the members of Base
, you need to tell the compiler that you expect a Base<T>
to have such a member. This is done by fully qualifying its name: Base<Type>::member
.