【问题标题】:enable_if with enum in g++ 4.8.1在 g++ 4.8.1 中使用 enum 的 enable_if
【发布时间】:2014-03-29 21:36:20
【问题描述】:

我想使用基于 g++ 枚举的 SFINAE。

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

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

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

编辑:
正如 sharth answered 代码是错误的,而 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;
}

【问题讨论】:

    标签: c++ templates enums g++ clang


    【解决方案1】:

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

    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) {}
    

    你会得到预期的行为。 Here is a demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2014-04-25
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多