On Sunday, 12 February 2017 08:42:31 UTC+2,
woodb...@gmail.com wrote:
> I was looking into how to serialize std::variant objects but have hit
> a problem.
>
> #include <variant>
>
> int main ()
> {
> constexpr ::std::variant<int, float> var = 3.3f;
> auto extract = ::std::get<var.index()>(var);
> }
>
> I have to make var constexpr in order to be able to use var.index()
> with std::get. But after I do that I can't write
>
> var = 7;
>
> If a variant isn't declared constexpr, I don't know how to get the
> value out of it. I'm new to constexpr stuff. Is there something
> I'm missing? Thanks in advance.
C++ is strongly typed language and variants, unions and/or ellipsis
arguments can't magically make it to go away. The 'get' needs to know
what type it returns compile time so if you can't tell it compile time
then you can't use it.
If you still want to use 'std::get' (I personally prefer visitors) then
use ordinary 'if' (or 'switch' or the like) to ensure beforehand
that you know what type that 'get' returns:
std::variant<int, std::string> v = "abc"; // no constexpr
if ( v.index() == 1 )
{
// here we know that get returns string
auto extract = std::get<1>(v);
}