英文:
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<typename Cat>
concept cat = requires(Cat cat) {
noexcept(Cat{42});
{ cat.meow() } -> std::same_as<int>;
};
static_assert(cat<Ragdoll>);
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 ->
or ;
:
template<typename Cat>
concept cat = requires(const Cat cat) {
{ Cat{42} } noexcept;
// If you wanted the member function to be noexcept too for example
{ cat.meow() } noexcept -> std::same_as<int>;
};
答案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<typename Cat>
concept cat = noexcept(Cat{42}) && requires(Cat cat) {
{ cat.meow() } -> std::same_as<int>;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论