在if-else块中实现类似SFINAE的效果

ein*_*ica 1 c++ templates conditional-compilation c++11

我希望能够写出类似的东西

template <typename T> void foo() {
    // ...
    if (is_nice<T>::value) {
        bar_which_is_defined_only_for_nice_types<T>();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译它(g ++ 4.9.3,没有优化)时,我得到了一个投诉bar_which_is_defined_only_for_nice_types.如何在不诉诸2定义的情况下达到预期效果foo()

Pra*_*ian 8

您可以根据标签发送标签 is_nice<T>

#include <type_traits>

template<typename T>
struct is_nice : std::false_type {};
template<>
struct is_nice<int> : std::true_type {};

template<typename T>
void do_nice_things(std::true_type)
{
    bar_which_is_defined_only_for_nice_types<T>();
}

template<typename T>
void do_nice_things(std::false_type)
{
}

template <typename T>
void foo()
{
    do_nice_things<T>(is_nice<T>{});
}
Run Code Online (Sandbox Code Playgroud)