Boost logo

Boost :

Subject: [boost] [variant] match()
From: Eelis (eelis_at_[hidden])
Date: 2015-01-07 03:41:04


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.




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