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 copy between variant of type and variant of type pointer

So I have two variants (I have shortened them, they have more types):

std::variant<int *, double *> PtrVariant;
std::variant<int, double> ValueVariant;

I want to copy value between them.

This does not work:

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

ValueVariant = *PtrVariant;

This works:

if (std::holds_alternative<int>(ValueVariant))
  ValueVariant = *std::get<int *>(PtrVariant);
else if (std::holds_alternative<double>(ValueVariant))
  ValueVariant = *std::get<double *>(PtrVariant);

Is there a way to copy values between them without checking what type is held by variant?

>Solution :

Use std::visit to do the dispatch:

std::visit([&](auto* p){ ValueVariant = *p; }, PtrVariant);
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