Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Serializing variant objects

30 views
Skip to first unread message

woodb...@gmail.com

unread,
Feb 12, 2017, 1:42:31 AM2/12/17
to
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.


Brian
Ebenezer Enterprises - In G-d we trust.
http://webEbenezer.net

Öö Tiib

unread,
Feb 12, 2017, 4:04:40 AM2/12/17
to
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);
}

woodb...@gmail.com

unread,
Feb 12, 2017, 10:21:59 PM2/12/17
to
+1 for example code.

It looks like std::variant can have zero or one types.
What's up with that? Prefer "float" to ::std::variant<float>.
Scott Meyers if you're listening to this, please put that in
your next book.


Brian
Ebenezer Enterprises
http://webEbenezer.net
0 new messages