1

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.

gst
  • 1,251
  • 1
  • 14
  • 32

1 Answers1

2
  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.

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • I do not really understand this term: `typename Composite::Parameters& parameters`. The :: is a scope resolution operator. So is `parameters` an object of `Parameters` of type `Composite` and the reference is being passed? – gst Aug 27 '19 at 13:59
  • 1
    `parameters` is a reference to the type `Parameters` which is declared in the scope of the (class) type `Composite`. (References aren't objects, and I'm not sure what you mean by "an object of `Parameters`") – L. F. Aug 27 '19 at 14:02