Boost logo

Boost :

Subject: Re: [boost] [variant] match()
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2015-01-07 13:39:53


Le 07/01/15 09:41, Eelis a écrit :
> Boost.Variant provides access through get() and visitors, but in C++11
> we can do so much better! :)
>
> For a boost::variant<A,B,C>, the attached small utility function
> match() lets you write:
>
> match(v,
> [](A & a){ cout << "it's a A!"; }
> [](B & b){ cout << "oh, a B!"; }
> [](C & c){ cout << "ah yes, a C!"; });
>
> Return values are supported. I think this really belongs in Boost. It
> makes variants much more usable.
>
> Regards,
>
> Eelis
>
> P.S. I have not attempted a C++98 implementation.
>
> P.S.2. Right after finishing my implementation, I discovered another,
> /vastly/ more complex implementation of the same thing:
>
> https://github.com/exclipy/inline_variant_visitor
>
> I'm not sure its complexity gives that implementation any advantages.
Hi,

IIUC the code, your implementation has some limitations as the user must
provide a function for each variant type and in the same order.

There is another one here [1] based on the overload function as defined
here [2]. There are some examples test here [3].

The same function can be used for optional/expected/any and many more
sum types (even if any is not a sum type, the selection of some possible
types makes it posible to see this selection as a sum type).

Best,
Vicente

[1]
https://github.com/viboes/tags/blob/master/include/yafpl/v1/functional/match.hpp
[2]
https://github.com/viboes/tags/blob/master/include/yafpl/v1/functional/overload.hpp
[3] https://github.com/viboes/tags/blob/master/test/variant/include_pass.cpp


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk