C++1z コンパイル時条件の論理演算

C++11時点で、コンパイル時条件をハンドリングするメタ関数として、以下があります:

C++1zからは、コンパイル時条件の論理演算を行う3つのメタ関数と、その変数テンプレート版が追加されます。

// <type_traits>
namespace std {
    // 論理積 (AND)
    template <class... B> struct conjunction;

    // 論理和 (OR)
    template <class... B> struct disjunction;

    // 否定 (NOT)
    template <class B> struct negation;

    // 変数テンプレート版
    template <class... B>
        constexpr bool conjunction_v = conjunction<B...>::value;
    template <class... B>
        constexpr bool disjunction_v = disjunction<B...>::value;
    template <class B>
        constexpr bool negation_v = negation<B>::value;
}

conjunctionコンパイル時条件の論理積 (AND) を求めるメタ関数です。boost::mpl::and_相当。integral_constant<boolに変換可能な型, B>のシーケンスを受け取って、それらを論理積した結果のbool_constantを継承してconjunctionが定義されます。

#include <type_traits>

int main()
{
    // 全ての条件がtrueなら結果がtrueとなる
    constexpr bool result = std::conjunction<
        std::true_type,
        std::is_void<void>,
        std::is_integral<int>
    >::value;
    static_assert(result);

    // 変数テンプレート版
    constexpr bool result2 = std::conjunction_v<
        std::true_type,
        std::is_void<void>,
        std::is_integral<int>
    >;
    static_assert(result2);
}

disjunctionコンパイル時条件の論理和 (OR) を求めるメタ関数です。boost::mpl::or_相当。integral_constant<boolに変換可能な型, B>のシーケンスを受け取って、それらを論理和した結果のbool_constantを継承してdisjunctionが定義されます。

#include <type_traits>

int main()
{
    // いずれかの条件がtrueなら結果がtrueとなる
    constexpr bool result = std::disjunction<
        std::false_type,
        std::is_void<char>,
        std::is_integral<int>
    >::value;
    static_assert(result);

    // 変数テンプレート版
    constexpr bool result2 = std::disjunction_v<
        std::false_type,
        std::is_void<char>,
        std::is_integral<int>
    >;
    static_assert(result2);
}

negation は、コンパイル時条件を否定 (NOT) するメタ関数です。integral_constant<boolに変換可能な型, B>を受け取って、それを否定したbool_constant<!B>を継承してnegationが定義されます。

#include <type_traits>

int main()
{
    // 条件を否定する
    constexpr bool result = std::negation<std::true_type>::value;
    static_assert(!result);

    // 変数テンプレート版
    constexpr bool result2 = std::negation_v<std::false_type>;
    static_assert(result2);
}

参照

お断り

この記事の内容は、C++1zが正式リリースされる際には変更される可能性があります。正式リリース後には、C++日本語リファレンスサイトcpprefjpの以下の階層の下に解説ページを用意する予定です。