Home > Enterprise >  How to delegate constructors for std::variant?
How to delegate constructors for std::variant?

Time:11-05

I have two structs A1 and A2 and another struct B has constructors for both. How do I write a delegating constructor for std::variant<A1,A2>?

#include <variant>
struct A1 {};
struct A2 {};
using A = std::variant<A1, A2>;

struct B {
  B(const A1 &){}
  B(const A2 &){}
  B(const A& a)
      :B(a) // <--- what do I put here to delegate like std::visit ?
  {}
};

int main(int argc, char *argv[]) {
    return 0;
}

I am looking for a clean modern way in the spirit of std::visit. I know that I can use a static member function to construct a B instance from A using std::visit and a lambda but that's not what I am asking for since I want to rely on implicit type conversion from A to B.

CodePudding user response:

If you can use the copy constructor, you can do this (not scalable but work in this case) :

struct B {
      B(const A1 &){}
      B(const A2 &){}
      B(const A& a)
          : B((a.index() == 0) ? B(std::get<0>(a)) : B(std::get<1>(a)))
      {}
    
    };

alternative with std::visit :

struct B {
   B(const A1 &){}
   B(const A2 &){}
   B(const A& a) : 
       B(std::visit([](const auto & x)
            {
                 return B(x);
            },a))
      {}
};
  • Related