gpt4 book ai didi

c++ - constexpr构造函数不满足要求,但还是constexpr。为什么?

转载 作者:可可西里 更新时间:2023-11-01 18:27:49 27 4
gpt4 key购买 nike

标准在 dcl.constexpr/6 中说明了模板 constexpr 函数/构造函数:

If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is still a constexpr function or constexpr constructor, even though a call to such a function cannot appear in a constant expression. If no specialization of the template would satisfy the requirements for a constexpr function or constexpr constructor when considered as a non-template function or constructor, the template is ill-formed, no diagnostic required.

有趣的部分是:

fail to satisfy the requirements for a ... constexpr constructor, that specialization is still a ... constexpr constructor

因此,即使构造函数被标记为 constexpr,它也不能用于常量表达式。

为什么会有这条规则?当函数不满足要求时,为什么不删除 constexpr

当前的行为在两个方面是不好的:

  • 非 constexpr-ness 不是在最近的可能位置捕获,而是在使用它的实际 constexpr 表达式处捕获。所以我们必须找到有问题的部分,其中 constexpr 被悄悄地删除了。
  • 一个旨在被静态初始化的对象(因为它有一个 constexpr 构造函数),将是 dynamically initialized没有任何错误/警告(因为构造函数不是“真正的”constexpr)。

这条规则是否有一些优点,可以平衡它的缺点?

最佳答案

此规则允许您编写模板化构造函数/函数并将其标记为 constexpr,即使它并不总是 constexpr(至少有时只是)。

例如,std::pairconstexpr constructors , 但它当然可以在常量表达式之外使用。

这是非常明智的,因为否则你将不得不复制所有这些函数(一次使用 constexpr ,一次不使用),即使代码完全相同。让我们甚至不考虑歧义。

因为通常不可能证明一个模板永远不能满足 constexpr,所以不需要对其进行诊断(但它的格式不正确,因此如果编译器可以证明这一点,则可以向您投诉给定情况)。

你是对的,如果你想指定“这个函数应该在常量表达式中可用”,这不是很有用,但这不是这个措辞的目的。

编辑:澄清一下,constexpr for functions 仅意味着“在常量表达式内求值是合法的”(更精确的措辞 here ), 不是 “只能在编译时求值”。相比之下,constexpr 变量必须使用常量表达式进行初始化。


另一个编辑:感谢@JackAidley,我们有确切的措辞要讨论!

If the instantiated template specialization of a constexpr function template would fail to satisfy the requirements for a constexpr function, the constexpr specifier is ignored and the specialization is not a constexpr function.

这个问题是“至少有一组参数可以对其函数进行常量计算”是“constexpr 函数要求”的一部分。因此,编译器无法实现此子句,因为不可能(通常)证明给定函数(或函数模板实例化)是否存在这样的集合。你要么必须进一步混淆这个要求,要么放弃这个方面。委员会似乎选择了后者。

关于c++ - constexpr构造函数不满足要求,但还是constexpr。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com