在g ++ 4.8.1中使用enum的enable_if

Eye*_*seo 2 c++ enums templates g++ clang

我想使用基于带有g ++的枚举的SFINAE.

使用g ++(4.8.1)编译时出错:
error: no type named ‘type’ in ‘struct std::enable_if<false, void>’

clang(3.2)编译它没有那个错误.

(a2和b2在两种情况下都会导致编译错误!)

编辑:
正如Sharth 回答的那样,代码是错误的,而clang 3.2只是"很好".
是否有不同的方法来实现此功能?


#include <type_traits>

enum Foo {
  A = 3,
  B = 4
};

template<Foo T> class Bar {
  const Foo foo_;

public:

  Bar() : foo_(T) {}

  template<typename = typename std::enable_if<T == A>::type>
  Bar(int x, int y, int z) : foo_(T) {}


  template<typename = typename std::enable_if<T == B>::type>
  Bar(int x, int y, int z, int w) : foo_(T) {}

  ~Bar() {}

};

int main(int argc, char const *argv[])
{
  Bar<A> a1(1,2,3);
  Bar<A> a2(1,2,3,4);
  Bar<B> b1(1,2,3,4);
  Bar<B> b2(1,2,3);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 7

您编写模板声明的方式不允许替换失败.您可以使用这样的默认虚拟模板参数来修复它:

template<Foo U = T, typename = typename std::enable_if<U == A>::type>
Bar(int x, int y, int z) : foo_(T) {}

template<Foo U = T, typename = typename std::enable_if<U == B>::type>
Bar(int x, int y, int z, int w) : foo_(T) {}
Run Code Online (Sandbox Code Playgroud)

你会得到预期的行为.这是一个演示.