Boost logo

Boost :

Subject: [boost] Interesting variadic template trick
From: Louis Dionne (ldionne.2_at_[hidden])
Date: 2013-11-17 23:25:34


Hi,

As some might know, I'm currently working on a reimplementation of the MPL
for C++11. In doing so, I came across a technique that I did not know of and
I thought I would share my discovery with the community. If this is already
well known, please excuse my ignorance.

The goal is to implement fast compile-time conjunction and disjunction.
It goes like this:

    template <typename ...T> void allow_expansion(T&&...);

    template <typename ...T>
    struct or_ {
        static constexpr bool value = !noexcept(
            allow_expansion((T::value ? throw : 0)...)
        );
    };

That's it! Note that disjunction is easily obtained in a similar way. The
benefit of this technique over traditional implementations is that it's
several times faster according to my benchmarks.

However, you might have noticed that short-circuit evaluation is not
respected so the above technique is only suitable when short-circuit
evaluation is not required.

If you find this interesting, see [1] for a collection of similar techniques.
The one I posted above seems to be the fastest with Clang and GCC.

Regards,

Louis Dionne

[1] https://gist.github.com/ldionne/7522393


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