Template Meta Programming 1

標準ライブラリのtype_traitsにあるis_sameを自分で実装してみましょう。 恐らく最も簡単なメタ関数の1つです。

integral_constant、true_type、false_typeも標準ライブラリ通りに準備します。 is_sameでは与えられた2つの型が同じであった場合の特殊化を行います。 このようにすることで、コンパイル時にもし与えられたtemplate引数が同じ型であった場合is_same<T, T>の定義が使われ、そうでない場合は標準の定義(特殊化されていないもの)が使われます。

結果はstatic constexprメンバ変数valueと、型typeを定義する事によって返します。

template <class T, T v>
struct integral_constant
{
    static constexpr T value = v;
    using value_type = T;
    using type = integral_constant<T, v>;
    constexpr operator T () const { return v; }
};

using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;

template<class S, class T>
struct is_same
{
    static constexpr bool value = false;
    using type = false_type;
};

template<class T>
struct is_same<T, T>
{
    static constexpr bool value = true;
    using type = true_type;
};

is_same<int, int>::valueなどとして使います。型が同じであればvalueはtrueに、異なればvalueはfalseになります。 enable_ifなどの条件に使えます。