Search code examples
c++sfinaepartial-specialization

SFINAE does not work as expected


I am reading this article and find this piece of code using SFINAE very interesting:

template<typename D, typename T2, typename... Args>
struct get_value_int<D, T2, Args...> {
    template<typename D2, typename T22, typename Enable = void>
    struct impl
        : std::integral_constant<int, get_value_int<D, Args...>::value> {};

    template<typename D2, typename T22>
    struct impl <D2, T22, std::enable_if_t<std::is_same<typename D2::type_id, typename T22::type_id>::value>>
        : std::integral_constant<int, T22::value> {};

    static constexpr const int value = impl<D, T2>::value;
};

As I understand, if the template class std::enable_if_t could not be instaniated, the first version of impl would be.

However, when I try to write a simpler piece of code, which I think pretty much the same as the one above, it gets compile errors. Do I misunderstand something here?

 template<typename T,typename N = void>
 class A
 {

 };

 template <typename T>
 class A<T, typename enable_if<false>::type>
 {

 };

Solution

  • SFINAE occurs in immediate context, here your condition doesn't depend of T so it is a hard failure, your code should be something like:

    template <typename T>
    class A<T, typename enable_if<condition<T>::value>::type>
    {
    };