I came across this code (simplified with basic types):
template <typename T>
class Base {
T t;
};
class Derived : public Base<short> {
public:
using Base<short>::Base;
};
int main() {
Derived::Base<long long> x;
printf("%lu\n", sizeof(x));
return 0;
}
It compiles and works (output is 8, which is the size of long long). It seems I can get Base<T>
for any type T
using Derived::Base
, even if Derived
is just a subclass of Base<short>
. (In the code I came across, Base
itself is not visible to main
.)
However, I don't quite understand this grammar and why it works.
Is Derived::Base
a template name, or a class, or a function (ctor)? It seems like a template name. Is the template name available in all classes that instantiate this template (like template name Base
is in Base<T>
for all type T
)? I'm so confused. Any explanation or pointer to cppreference or the C++ standard are appreciated.
If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class. We can use this facility to build generic versions of the Class Adapter Pattern – using a derived template class to modify the interface of the base class.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.
Instances of the derived class are instances of the base class.
A base class is an existing class from which the other classes are derived and inherit the methods and properties. A derived class is a class that is constructed from a base class or an existing class. 2. Base class can't acquire the methods and properties of the derived class.
From en.cppreference.com/injected-class-name:
In the following cases, the injected-class-name is treated as a template-name of the class template itself:
- it is followed by <
- [..]
So Base
inside Base<T>
is, depending of context, a class or a template name.
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