gpt4 book ai didi

c++ - 声明 constexpr 函数或方法

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

我想知道是否对必须声明 constexpr 函数和方法的位置有任何限制,就像内联函数和方法一样。

我知道内联函数或方法必须写在头文件中,以便编译器可以在调用它们的地方访问它们的定义。如果 constexpr 有类似的东西,那将是有道理的,但我无法在这一点上找到任何东西......

所以基本上我的问题是:

  • 我能否在头文件中编写 constexpr 函数的定义而不冒重复符号的风险?

  • 我可以将constexpr函数或方法的声明和定义分开吗?

最佳答案

您定义 constexpr 函数的位置会影响您如何使用它。特别是:

C++14[expr.const]p2:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • an invocation of an undefined constexpr function or an undefined constexpr constructor;

所以你不能在常量表达式中使用constexpr函数(模板参数,constexpr变量初始化器,需要静态求值的全局变量初始化器,数组绑定(bind)表达式,也许其他)如果它只是被声明但尚未定义。

同样,正如dyp评论的那样,

C++14[dcl.constexpr]p2

constexpr functions and constexpr constructors are implicitly inline (7.1.2).

这意味着您第一个问题的答案:在 header 中定义 constexpr 函数不会导致重复符号。这也意味着如果您在 header 中声明一个 constexpr 函数,然后在翻译单元中调用它,即使只是在运行时,“内联函数应该在每个使用它的翻译单元中定义。”来自 C++14[basic.def.odr]p4。

请注意,常量表达式和调用的规则通常是不同的:调用通常要求定义在翻译单元的某处:常量表达式要求定义在之前 常量表达式。

关于c++ - 声明 constexpr 函数或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152418/

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