SCARY metafunctions

I just watched Odin Holmes’s half-session from C++Now 2017 titled “Type-Based Template Metaprogramming is Not Dead.” Honestly, I found it mostly pretty hard to follow. (Note to presenters: The video recording will pick up your mouse cursor, but not your laser pointer!) But there was one “oooh” moment right around 15 minutes in. Context: compile-time performance.

Odin shows this classic code:

template<bool B, class T, class F>
struct conditional {
    using type = T;
};

template<class T, class F>
struct conditional<false, T, F> {
    using type = F;
};

template<bool B, class T, class F>
using conditional_t = typename conditional<B, T, F>::type;

And then he flips to the next slide:

template<bool B>
struct conditional {
    template<class T, class F> using f = T;
};

template<>
struct conditional<false> {
    template<class T, class F> using f = F;
};

template<bool B, class T, class F>
using conditional_t = typename conditional<B>::template f<T, F>;

Mind: blown.

The “classic” approach is so obviously inefficient by comparison; but this is the first time I’ve seen Odin’s approach presented. I wonder if there’s any chance of getting std::conditional_t defined this way in the actual Standard.


The title of this post is a reference to SCARY Iterators, which apply the same “Don’t Repeat Yourself” approach but in a less “meta” area of template programming.

The acronym SCARY describes assignments and initializations that are Seemingly erroneous (appearing Constrained by conflicting generic parameters), but Actually work with the Right implementation (unconstrained bY the conflict due to minimized dependencies).

Posted 2018-07-09