为什么用enable_if编译错误

Leo*_*sky 28 c++ templates metaprogramming sfinae enable-if

为什么这不能用gcc48和clang32编译?

#include <type_traits>

template <int N> 
struct S {

    template<class T> 
    typename std::enable_if<N==1, int>::type
    f(T t) {return 1;};

    template<class T> 
    typename std::enable_if<N!=1, int>::type
    f(T t) {return 2;};
};

int main() {
    S<1> s1;
    return s1.f(99);
}
Run Code Online (Sandbox Code Playgroud)

GCC错误:

/home/lvv/p/sto/test/t.cc:12:2: error: no type named ‘type’ in ‘struct enable_if<false, int>’
  f(T t) {return 2;};
  ^
Run Code Online (Sandbox Code Playgroud)

CLANG错误:

/home/lvv/p/sto/test/t.cc:11:26: error: no type named 'type' in 'std::enable_if<false, int>'; 'enable_if' cannot be used to
      disable this declaration
        typename std::enable_if<N!=1, int>::type
                                ^~~~
/home/lvv/p/sto/test/t.cc:16:7: note: in instantiation of template class 'S<1>' requested here
        S<1> s1;
             ^
Run Code Online (Sandbox Code Playgroud)

编辑 - 解决方案

我接受了Charles Salvia的回答,但由于实际原因,我无法使用提议的解决方法(专注于N).我找到了适合我的其他解决方法.使enable_if依赖于T:

typename std::enable_if<(sizeof(T),N==1), int>::type
Run Code Online (Sandbox Code Playgroud)

Cha*_*via 21

因为您在函数模板中enable_if不使用模板参数而使用T.如果要在struct S具有特定模板参数值时专门用于,则N需要使用类模板特化.

template <int N, class Enable = void> 
struct S {  };

template <int N>
struct S<N, typename std::enable_if<N == 1>::type>
{
  ....
};
Run Code Online (Sandbox Code Playgroud)


小智 10

好吧,我不确定你想做什么,但也许这段代码会有所帮助:

#include <iostream>

template <int N>
struct S {

    template<class T=int>
    typename std::enable_if<N==1, T>::type
    f(T t) {return 1;}

    template<class T=int>
    typename std::enable_if<N!=1, T>::type
    f(T t) {return 2;}
};

int main()
{
    S<1> s1;
    S<2> s2;
    std::cout << s1.f(99) << " " << std::endl << s2.f(5);
}
Run Code Online (Sandbox Code Playgroud)

这打印1和2.


Pau*_* II 8

使用默认的布尔模板参数,如下所示:

template <int N> 
struct S {

    template<class T, bool EnableBool=true> 
    typename std::enable_if<N==1 && EnableBool, int>::type
    f(T t) {return 1;};

    template<class T, bool EnableBool=true> 
    typename std::enable_if<N!=1 && EnableBool, int>::type
    f(T t) {return 2;};
};
Run Code Online (Sandbox Code Playgroud)


Ant*_*ony 6

要开始std::enable_if这样的工作,你依靠SFINAE.不幸的是,在你声明的那一刻

S<1> s1;
Run Code Online (Sandbox Code Playgroud)

它将实例化所有S<1>的成员声明.如果S<1>是一个结构不良的建筑,SFINAE只会在这一点上发挥作用.它不是.不幸的是,它包含一个无效的函数,因此实例化S<>是无效的.

对于这样的事情,我可能会推迟一个单独的模板结构:

template <bool B>
struct f_functor {
    template <typename T>
    static int f(T t) { return 1; }
};

template <>
struct f_functor<false> {
    template <typename T>
    static int f(T t) { return 2; }
};

template <int N> 
struct S {

    template<class T> 
    typename int f(T t) { return f_functor<N==1>::f(t); }
};
Run Code Online (Sandbox Code Playgroud)