gst
gst

Reputation: 1285

Class inheritance of template parameters in C++

I am new to C++ and happen to come across a code which looks like this :

template<class T, class Composite> class CompositeTester: public Composite
{
  public: 
    CompositeTester(T* instance, const typename Composite::Parameters& parameters) : Composite(parameters)
    {
        singletonInstances_[parameters.instanceIndex] = instance;
    }
}
  1. The inheritance is not so clear to me, because the inheritance is from the template class arguments itself. What is this concept known as?
  2. In the contructor CompositeTester, I realise that the instance of Composite is created with parameters as arguments. But this syntax is quite difficult to understand const typename Composite::Parameters. How to intrepret this syntax? Is defining an object of class composite, even before it exists valid?

  3. singletonInstances_[parameters.instanceIndex] = instance. Is here a new variable created for parameters.instanceIndex ? There exists no definition in the source code for class Composite::Parameters or class Compositeapart from what I mentioned in the question here.

Upvotes: 1

Views: 64

Answers (1)

L. F.
L. F.

Reputation: 20609

  1. This is known as the curiously recurring template pattern.

  2. typename is used here to denote a dependent type name. Without it, the compiler will parse the qualified name as a non-type entity. See our FAQ on this: Where and why do I have to put the "template" and "typename" keywords?

  3. This is ill-formed in standard C++ because singletonInstances_ is not declared. If it is declared in the base class, you need to use this-> to make it a dependent name.

Upvotes: 2

Related Questions