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

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

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

问题

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

class Ragdoll {
    int age_ = -1;
public:
    Ragdoll(int age) /* noexcept */ : age_(age) {}

    int meow() const;
    int lose_hair();
};

template<typename Cat>
concept cat = requires(Cat cat) {
    noexcept(Cat{42});
    { cat.meow() } -> std::same_as<int>;
};

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.

class Ragdoll {
    int age_ = -1;
public:
    Ragdoll(int age) /* noexcept */ : age_(age) {}

    int meow() const;
    int lose_hair();
};

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

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

以下是翻译好的部分:

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

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

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

答案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.

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

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:

确定