0

In recent SO answer, part of the snippet I'm unable to understand whats happening,

struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
    using base = std::variant<std::vector<VariableDepthList>, int>;
public:
    using base::base;
    VariableDepthList(std::initializer_list<VariableDepthList> v) : base(v) {}
};

base(v) is calling ctor of base class, if so what is equivalent to without having using base::base?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
TruthSeeker
  • 1,539
  • 11
  • 24
  • 3
    You don't need the `using base::base;` part to use `base(v)`: the latter is always (independent of the `using` declaration) constructing the base object, The `using` declaration is used to expose the `base` ctors in your `VariableDepthList`. – Dietmar Kühl Dec 22 '21 at 17:57
  • @DietmarKühl: If `using base::base` part then i see the error. [DEMO](https://www.godbolt.org/z/fj4qbGT3K) – TruthSeeker Dec 22 '21 at 18:11
  • 3
    as I stated: you don't need the `using` declaration to define the ctor. You may need it, depending on your use, to bypass you constructor and directly use the base class's ctor. As you don't have a constructor viable of `std::initializer_list` but `{ 1 }` is an `std::initializer_list`, the constructor of the base class is used directly. – Dietmar Kühl Dec 22 '21 at 18:15

1 Answers1

2

what is equivalent to without having using base::base?

You replace it with what base is an alias for:

struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
public:
    VariableDepthList(std::initializer_list<VariableDepthList> v) :
        std::variant<std::vector<VariableDepthList>, int>(v) // was "base(v)"
   {}
};

Note though that without using the base class constructors, they will not be accessible to users of VariableDepthList.

If you do want the base class constructors to be available, without creating the alias base:

struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> {
private:
public:
    using std::variant<std::vector<VariableDepthList>, int>::variant;
    
    VariableDepthList(std::initializer_list<VariableDepthList> v) :
        std::variant<std::vector<VariableDepthList>, int>(v) // was "base(v)"
   {}
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • I see compilation error for the same. [DEMO](https://www.godbolt.org/z/EefjKz1sf). I thought something beyond just a replacement is happening underneath. – TruthSeeker Dec 22 '21 at 18:05
  • 1
    @TruthSeeker You get a compilation error because you didn't make the base class constructors available. I updated the answer. – Ted Lyngmo Dec 22 '21 at 18:14