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 struct
s) 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.