c++ - static_assert with nonconstexpr objects in hana's tutorial

标签 c++ constexpr static-assert

阅读hana's tutorial ,我想知道 static_assert 如何按预期工作:

template <typename Any>
auto switch_(Any& a) {
  return [&a](auto ...cases_) {
    auto cases = hana::make_tuple(cases_...);

    auto default_ = hana::find_if(cases, [](auto const& c) {
      return hana::first(c) == hana::type_c<default_t>;
    });

    static_assert(default_ != hana::nothing,
      "switch is missing a default_ case");

    // ...
  };
}

文档明确指出 default_ 不是 constexpr 对象,因此,即使这些类型的 operator!= 重载是constexpr 函数,表达式 default_ != hana::nothing 不能是常量表达式,因为它的参数之一不是。

教程说:

Notice how we can use static_assert on the result of the comparison with nothing, even though default_ is a non-constexpr object? Boldly, Hana makes sure that no information that's known at compile-time is lost to the runtime, which is clearly the case of the presence of a default_ case.

教程在该段中指的是什么,或者该表达式是如何工作的?

最佳答案

您误解了 constexpr 的要求。您可以将非 constexpr 参数传递给 constexpr 函数,结果可以constexpr

玩具示例:

struct foo {
  int x;
  foo(int in):x(in){}
  friend constexpr bool operator==(foo const&, foo const&) { return true; }
};

然后

foo a{1}, b{2};
static_assert( a==b, "works" );

完全有效。

哎呀,我可以在堆上分配那些 foo,并且 == 仍然会计算为 constexpr 表达式。

default_ 不是 constexpr,但可以仅使用 type 的信息将其与 nothing 进行比较default_,在编译时可用。 Nothing 比较等于 hana::nothing 但(的另一个实例)nothing。

struct toy_nothing_t {
  friend constexpr bool operator==(toy_nothing_t const&, toy_nothing_t const&) {
    return true;
  }
  template<class T>
  friend constexpr bool operator==(T const&, toy_nothing_t const&) {
    return false;
  }
  template<class T>
  friend constexpr bool operator==(toy_nothing_t const&, T const&) {
    return false;
  }
};

这个 toy_nothing_t 具有相似的属性。

关于c++ - static_assert with nonconstexpr objects in hana's tutorial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44143209/

相关文章:

c++ - 为什么在 constexpr 非成员函数中访问全局非常量变量是不合法的

c++ - 使用 static_assert 检查 Q_OBJECT 宏

c++ - 如何在编译时检查类是否是抽象的?

c++ - 在构造函数初始化列表中初始化 std::vector 数组

c++ - <algorithm> 用对象进行 vector 排序?

c++ - 将 constexpr 与 getenv (或替代方案)一起使用

c++ - 此错误消息是否正确 : non-type template argument is not a constant expression

c++ - static_assert 和类模板

C++ 项目在glewinit()之后崩溃

c++ - #define 指令中的 sizeof 运算符