gpt4 book ai didi

c++ - 访问静态 constexpr float 成员时 undefined reference

转载 作者:可可西里 更新时间:2023-11-01 17:40:16 24 4
gpt4 key购买 nike

此代码有效:

struct Blob {
static constexpr int a = 10;
};

int main() {
Blob b;
auto c = b.a;
}

但是如果我将 int 更改为 float 我会得到一个错误:

struct Blob {
static constexpr float a = 10.0f;
};

/tmp/main-272d80.o: In function main': main.cpp:(.text+0xe):
undefined reference to
Blob::a'

为什么我不能以这种方式使用 constexpr float

编译器:Ubuntu clang 版本 3.5.0-4ubuntu2 (tags/RELEASE_350/final)

在gcc version 4.9.1 (Ubuntu 4.9.1-16ubuntu6)上测试,没有报错。

编辑:

如果我使用 -O1、-O2、-O3 或 -Os 但使用 -O0 会失败

最佳答案

C++11 阅读

A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied.

很明显,l-t-r 转换会立即应用,浮点类型的 constexpr 变量可以按照 [expr.const]/(2.7.1) 出现在常量表达式中:

A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression [..]

  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • a glvalue of literal type that refers to a non-volatile object defined with constexpr, or that refers to a sub-object of such an object, or

似乎是一个 Clang 错误。

关于c++ - 访问静态 constexpr float 成员时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264279/

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