Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delegate constructors for std::variant?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)))
  {}

};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading