ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 在hana的教程中使用nonconstexpr对象的static_assert

2019-08-23 19:07:59  阅读:191  来源: 互联网

标签:static-assert c constexpr


阅读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对象,因此,即使运算符!=对这些类型的重载是constexpr函数,表达式default_!= hana :: nothing也不能是常量表达式,因为它的一个参数是“T.

教程说:

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 args传递给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,但只能使用default_的类型信息来完成它的比较,该信息在编译时可用.没有什么能比得上hana :: 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有类似的属性.

标签:static-assert,c,constexpr
来源: https://codeday.me/bug/20190823/1700245.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有