What is using T::T

Viewed 69

I read this article but I don't understand the meaning of this part of the code:

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

It must be something simple as "make visible all names from namespace" but I don't completely understand it.

2 Answers

T is the base class.

T::T is/are the constructor(s) of the base class T. A constructor has the same name as the class being constructed.

using T::T; brings the constructor(s) of the base class into the current scope, which is the derived class counted.

This line allows counted to be constructed using any constructor that T allows.

make visible all names from namespace

No, because T isn't a namespace. You can't derive from a namespace.

The using keyword has more than one meaning.

You're thinking of the using directive for namespaces, but the using declaration works for both namespace members (at namespace scope) and class members (inside a class). Since we already established T is not a namespace, this is obviously the second case.

Inside a class using T::member would normally just prevent base-class names being hidden by the derived class, but T::T means the base class constructor, which as a special case inherits constructors from T.

template <typename T> struct counted : T
{
  using T::T; // now counted<T> can directly use any of T's constructors
};
Related