31

为什么这不能用 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);
}

海合会错误:

/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;};
  ^

叮当错误:

/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;
             ^

编辑 - 解决方案

我已经接受了 Charles Salvia 的回答,但出于实际原因,我无法使用建议的解决方法(专门研究 N)。我找到了其他适合我的解决方法。使enable_if依赖T

typename std::enable_if<(sizeof(T),N==1), int>::type
4

5 回答 5

21

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

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

template <int N>
struct S<N, typename std::enable_if<N == 1>::type>
{
  ....
};
于 2012-12-20T02:41:14.383 回答
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);
}

这将打印 1 和 2。

于 2014-10-31T15:28:29.497 回答
9

std::enable_if像这样工作,您依赖于 SFINAE。不幸的是,在您宣布

S<1> s1;

它将实例化所有S<1>的成员声明。S<1>如果 SFINAE是一个格式不正确的构造,那么此时 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); }
};
于 2012-12-20T02:51:14.573 回答
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;};
};
于 2014-08-16T20:46:52.617 回答
1

对于这种情况,您可以考虑根本不使用 enable_if。可以简单地专门化 f:

template <int N> 
struct S {
    template<class T> int f(T t);
};

template<int N>
template<class T>
int S<N>::f(T t) { return 2; }

template<>
template<class T>
int S<1>::f(T t) { return 1; }

int main() {
    S<1> s1;
    return s1.f(99);
}
于 2012-12-20T08:50:16.473 回答