0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Hint 1: `T` is the template argument and you inherited this class. Hint 2: `Classname::Classname` is the name of the constructor of a class. – tkausl Sep 13 '22 at 13:58
  • 2
    In this context, using is used to inherit the base class's (`T`) constructors: https://stackoverflow.com/questions/347358/inheriting-constructors – clcto Sep 13 '22 at 13:58
  • 2
    There are no namespaces involved. `T` is a base class and in that case this is special syntax to inherit constructors of the base. (It has the different meaning than `using` has in other contexts.) – user17732522 Sep 13 '22 at 13:59
  • Exact duplicate of: [Questions about template and typename](https://stackoverflow.com/questions/54884292/questions-about-template-and-typename/54884572#54884572) – Jason Sep 13 '22 at 17:33

2 Answers2

7

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.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

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
};
Useless
  • 64,155
  • 6
  • 88
  • 132