Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is template name available in derived class (the base class is an instance of the template)?

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.

like image 981
hhggdd Avatar asked Jul 28 '19 20:07

hhggdd


People also ask

Can a derived class be template?

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.

What is template What is the need of template declare a template 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.

Which class is an instance of base class?

Instances of the derived class are instances of the base class.

What is the difference between a base class and a derived 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.


1 Answers

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.

like image 143
Jarod42 Avatar answered Oct 27 '22 01:10

Jarod42