enable_if + type template,没有SFINAE(enable_if_c没有boost?)

时间:2013-02-14 03:13:24

标签: c++ c++11 g++ sfinae enable-if

我从阅读各篇文章中了解到以下内容不应该编译。

#include <type_traits>
#include <iostream>

template <bool is_constant> struct A {
  // Need to fix this for g++-4.7.2
  // implicit conversion to int iff is_constant == true statically
  template <class = typename std::enable_if<is_constant>::type>
  constexpr operator int() const {
    return 10;
  }                                             
};

int main()
{
  A<true> a;
  int i = 2 + a;   
  std::cout << i << "\n";

  A<false> b;
  // int i = 2 + a;   // compilation error
}

仍然,clang 3.2接受此代码版本,它运行正常。我的理解是它使用了内部版本的enable_if_c。 现在我希望在gcc下进行编译,但不接受它。 我知道拥有一个实际的类型会很好,并按照其他帖子使用SFINAE。

就我而言:

  • 我正在尝试定义一个运算符,所以我不能讨论具有某些默认类型/值的额外参数 - &gt;好像我不能使用SFINAE。
  • 我不能使用继承,因为我必须保留所有constexpr。
  • 由于项目要求,我无法在我的代码(enable_if_c)中使用任何boost include

我有出路吗?

1 个答案:

答案 0 :(得分:0)

为什么不使用专业化?

#include <iostream>

template <bool is_constant>
struct A {};

template <>
struct A<true> {
    constexpr operator int() const {
        return 10;
    }
};

int main()
{
    A<true> a;
    int i = 2 + a;
    std::cout << i << "\n";

    A<false> b;
    // int ii = 2 + b;   // compilation error
}

这是非常简单和交叉编译的方法......