How to copy between variant of type and variant of type pointer

72 Views Asked by At

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:

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?

1

There are 1 best solutions below

0
Jarod42 On BEST ANSWER

Use std::visit to do the dispatch:

std::visit([&](auto* p){ ValueVariant = *p; }, PtrVariant);