Boost logo

Boost :

Subject: [boost] A more convenient Variant visitation syntax
From: Kevin Wu Won (exclipy_at_[hidden])
Date: 2012-04-14 11:00:38

While Boost Variant is a wonderful library that fills a genuine hole
in the C++ language, it is not as nice to use as it could be. The
"correct" way to unwrap a variant is to apply a static visitor, but
this method carries a high syntactic burden because it needs the user
to define a class (probably somewhere far away) just so they can
"switch" on the type of the object stored in the variant.

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

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.

Here's the code:

What do you think? This started out for me as an exercise to learn
template metaprogramming and C++11, but hopefully, it can actually
evolve into something useful.

Boost list run by bdawes at, gregod at, cpdaniel at, john at