enable_if+类型模板,无SFINAE(enable_if_c无boost?)

enable_if + type template, no SFINAE (enable_if_c without boost ?)

本文关键字:enable if boost SFINAE if+ 类型      更新时间:2023-10-16

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

#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
  • 我也不能使用继承,因为我必须保持所有常量表达式
  • 由于项目要求,我不能在代码中使用任何boost-include(enable_if_c)

我有出路吗?

为什么不使用专业化?

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

这是一种非常直接和跨编译器的方法。。。