C++:如何编写一个要求构造函数是noexcept的concept?

huangapple go评论96阅读模式
英文:

C++: How to write a concept that demands that constructor is noexcept?

问题

如何编写一个要求类具有noexcept构造函数的概念?例如,在Clang 15.0.7中,以下static_assert是成立的,尽管我觉得它不应该成立。

  1. class Ragdoll {
  2. int age_ = -1;
  3. public:
  4. Ragdoll(int age) /* noexcept */ : age_(age) {}
  5. int meow() const;
  6. int lose_hair();
  7. };
  8. template<typename Cat>
  9. concept cat = requires(Cat cat) {
  10. noexcept(Cat{42});
  11. { cat.meow() } -> std::same_as<int>;
  12. };
  13. static_assert(cat<Ragdoll>);

那么在概念中,noexcept表达式究竟是在做什么呢?(也可以链接一些好的概念教程)

英文:

How do I write a concept that demands that the class has a noexcept constructor? For example, the following static_assert is true in Clang 15.0.7, although I feel that it shouldn't.

  1. class Ragdoll {
  2. int age_ = -1;
  3. public:
  4. Ragdoll(int age) /* noexcept */ : age_(age) {}
  5. int meow() const;
  6. int lose_hair();
  7. };
  8. template&lt;typename Cat&gt;
  9. concept cat = requires(Cat cat) {
  10. noexcept(Cat{42});
  11. { cat.meow() } -&gt; std::same_as&lt;int&gt;;
  12. };
  13. static_assert(cat&lt;Ragdoll&gt;);

What is the noexcept expression doing then anyway in the concept? (Feel free to also link any good concepts tutorials)

答案1

得分: 5

以下是翻译好的部分:

  1. template<typename Cat>
  2. concept cat = requires(const Cat cat) {
  3. { Cat{42} } noexcept;
  4. // 如果你想要成员函数也是 noexcept 的话,可以这样写
  5. { cat.meow() } noexcept -> std::same_as<int>;
  6. };
英文:

You can check if an expression is noexcept in a requires expression with a noexcept before the -&gt; or ;:

  1. template&lt;typename Cat&gt;
  2. concept cat = requires(const Cat cat) {
  3. { Cat{42} } noexcept;
  4. // If you wanted the member function to be noexcept too for example
  5. { cat.meow() } noexcept -&gt; std::same_as&lt;int&gt;;
  6. };

答案2

得分: 2

这似乎有效(在触发static_assert的意义上),尽管我更愿意以某种方式在requires子句中指定它。

英文:

Okay, apparently the following works (in the sense that it triggers the static_assert), although I'd prefer to somehow specify it in the requires clause.

  1. template&lt;typename Cat&gt;
  2. concept cat = noexcept(Cat{42}) &amp;&amp; requires(Cat cat) {
  3. { cat.meow() } -&gt; std::same_as&lt;int&gt;;
  4. };

huangapple
  • 本文由 发表于 2023年5月15日 04:31:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定