Boost logo

Boost :

Subject: Re: [boost] A more convenient Variant visitation syntax
From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2012-04-14 18:00:46


On Sat, Apr 14, 2012 at 5:00 PM, Kevin Wu Won <exclipy_at_[hidden]> wrote:
> [...]
> I came up with a solution where the handler functions can be specified
> inline with C++11 lambdas.  Here's an example:
>
>    boost::variant< int, std::string > u("hello world");
>    int result = match(u,
>        [](int i)                   -> int { return i; },
>        [](const std::string & str) -> int { return str.length(); });
>
> The `match` function accepts the variant followed by the handler
> functions.  The functions can be specified in any order.  It will fail
> to compile if the functions do not match the types of the variant, if
> the return types are not all the same, or if a non-unary function is
> supplied.
>
> This is C++11 only because it's quite pointless without lambda
> functions.  I've tested it with gcc 4.7.  It doesn't work on gcc 4.6,
> which can't handle the variadic templates.

It should be possible to implement the same feature on gcc 4.6. Take a look at

https://github.com/gpderetta/Experiments/blob/scheduler/match.hpp

(test: https://github.com/gpderetta/Experiments/blob/scheduler/match_test.cc)

which, given a set of monomorphic function objects create a
polymorphic function object (of arbitrary arity). It can be used with
boost variant like this:

 boost::variant< int, std::string > u("hello world");
   int result = boost::apply_visitor(u, match(
       [](int i) { return i; },
       [](const std::string & str) { return str.length(); }));

The 'match' function (interestingly we used the same name :) ) works
fine on gcc 4.6; the implementation is surprisingly simple and it is
completely indipendeng from boost.variant. If you are interested feel
free to use the code and/or incorporate it in your library (it is
under the boost license).

HTH,

-- 
gpd

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