【问题标题】:enable_if + type template, no SFINAE (enable_if_c without boost ?)enable_if + type 模板,没有 SFINAE(没有 boost 的 enable_if_c ?)
【发布时间】:2013-02-14 03:13:24
【问题描述】:

我通过阅读各种帖子了解到以下内容不应该编译。

#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。

就我而言:

  • 我正在尝试定义一个运算符,因此我不能对具有某些默认类型/值的额外参数大惊小怪 -> 看来我不能使用 SFINAE。
  • 我也不能使用继承,因为我必须保留一切 constexpr。
  • 由于项目要求,我无法在我的代码 (enable_if_c) 中使用任何增强功能

我有出路吗?

【问题讨论】:

  • static_assert(is_constant) 呢?
  • 为什么constexpr 表示不能使用继承?

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


【解决方案1】:

为什么不使用专业化?

#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
}

这是非常直接的跨编译器方法...

【讨论】:

  • 你知道吗...为什么不呢?结果我的代码变得如此复杂,以至于我忘记了这个简单的选项......我必须复制相当多的代码,因为我无法继承(文字类型和 constexpr)。但我至少现在可以忍受!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多