0

I found this article: https://tristanbrindle.com/posts/beware-copies-initializer-list and I have some question about part of the presented code:

First:
I think that is something about dependent name but I am not sure what is a purpouse of this part:

 template <typename T>
    typename instance_counter<T>::counter instance_counter<T>::icounter{};

And second one:

template <typename T>
struct counted : T, private instance_counter<T>
{
    using T::T;
};

Could somebody give me an explanation about these codes?

KeyB0rys
  • 392
  • 5
  • 13
  • What's your actual question – Hatted Rooster Feb 26 '19 at 11:23
  • 1
    Hi! I think this question is too broad. If you have multiple questions, please, ask them separately. Also, try to explain your problem better. Do you want to know what "depenedent name" is or what this code does or maybe what the word "typename" does here? Please, consider reading https://stackoverflow.com/help/how-to-ask. – Piotr Siupa Feb 26 '19 at 11:23

1 Answers1

4

Could somebody give me an explanation about these codes?

template <typename T>
typename instance_counter<T>::counter instance_counter<T>::icounter{};

This is the initialization of a static variable declared in the instance_counter template (see the static struct counter { /* ... */ } icounter; in the blog post). See this thread for more info on the initialization of static data members. The definition refers to a nested name of a template (counter), and the compiler defaults to consider it a name for a value, not a type. To change this default interpretation, you need to prepend typename. See this thread for details.

template <typename T>
struct counted : T, private instance_counter<T>
{
    using T::T;
};

Here, the template counted inherits publicly from T (public inheritance is the default for structs) and privately from instance_counter<T>. The public inheritance part together with using T::T (which brings in all ctor overloads of T) is used to provide the same interface as the class the template is instantiated with (e.g. string in the post). The private inheritance part means is-implemented-in-terms-of and makes sure the instance_counter machinery is pulled in for the newly instantiated class type, with the output being generated in the destructor.

lubgr
  • 37,368
  • 3
  • 66
  • 117