C++0x enable_if

C++0x に含まれる enable_if は Boost のものとはちょっと違います。


Boost では、 enable_if, disable_if, enable_if_c, disable_if_c が提供されていますが

C++0x では enable_if だけが提供され、 Boost の enable_if_c に相当します。
(パラメータで、 bool を返すメタ関数ではなく bool 値を受け取る)

namespace std {
    template <bool, class T = void> struct enable_if;
}

なので、 disable_if 相当のことをしたい場合はパラメータに与える bool 値を逆(NOT)にする必要があります。

#include <iostream>
#include <type_traits>

using namespace std;

template <class T>
void foo(const T&, typename enable_if<is_integral<T>::value>::type* = 0)
{
    cout << "integral" << endl;
}

template <class T>
void foo(const T&, typename enable_if<!is_integral<T>::value>::type* = 0) // disable_if
{
    cout << "other" << endl;
}

int main()
{
    foo(3);    // integral
    foo(3.14); // other
}


C++0x言語拡張まとめ