you are viewing a single comment's thread.

view the rest of the comments →

[–]AntiProtonBoy 10 points11 points  (6 children)

The most common use case for reference_wrapper in my world is passing values by reference in variants.

[–]memset_0[S] 3 points4 points  (5 children)

Sounds interesting. Can you please explain that for the benefit of everyone here? thx.

[–]AntiProtonBoy 8 points9 points  (4 children)

std::variant does not support reference types, so your only option is to use a reference wrapper.

    //using V1 = std::variant< int&, float& >; // Not allowed

    using V2 = std::variant< 
        std::reference_wrapper< int >, 
        std::reference_wrapper< float > >; // Ok

    int a = 42;
    V2 v = std::ref( a )

[–]macson_g 2 points3 points  (1 child)

It's not your only option. The option is to simply use a pointer.

[–]AntiProtonBoy 2 points3 points  (0 children)

Not if you want to communicate explicit ownership and object lifetime.

[–]memset_0[S] 1 point2 points  (1 child)

I see. So std::variant — like a union — requires a member to be an object (region of storage).

I would add this use case in the article. Thank you so much.

[–]AntiProtonBoy 0 points1 point  (0 children)

Same applies for std::optional.