gpt4 book ai didi

c++ - 为什么不允许 "inlined"静态常量,整数除外?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:50 25 4
gpt4 key购买 nike

Possible Duplicate
Why can't I have a non-integral static const member in a class?

struct Example
{
static const int One = 1000; // Legal
static const short Two = 2000; // Illegal
static const float Three = 2000.0f; // Illegal
static const double Four = 3000.0; // Illegal
static const string Five = "Hello"; // Illegal
};

#2、#3、#4 和#5 是非法的吗?

我想我知道 #5 的原因:编译器需要一个“真正的”字符串对象(因为它不是内置类型)并且不能盲目地将 Five 替换为 "Hello" 就像是 #define Five "Hello"。但如果是这样的话,编译器难道不能在 .obj 文件中留下一个提示,告诉链接器在某处自动创建一个 string Five 的实例吗?

对于#3 和#4,尤其是#2(笑!)...我真的看不出任何可能的原因! float 和 double 是内置类型,就像 int 一样! short 只是一个(可能)更短的整数。


编辑:我正在使用 Visual Studio 2008 对其进行编译。我认为所有编译器在这种情况下的行为都相同,但显然 g++ 编译得很好(#5 除外)。 VS 为该片段给出的错误是:

    error C2864: 'Example::Two' : only static const integral data members can be initialized within a class    error C2864: 'Example::Three' : only static const integral data members can be initialized within a class    error C2864: 'Example::Four' : only static const integral data members can be initialized within a class    error C2864: 'Example::Five' : only static const integral data members can be initialized within a class

最佳答案

int 和 short 是合法的,如果你的编译器不允许它们那么你的编译器就失败了:

9.4.2/4: ... If the static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression.

我认为,在 C++ 标准中, float 和 double 没有像整数类型那样被特殊对待的原因是,C++ 标准担心 float 和 double 的算术运算可能会被巧妙地处理在编译机器上与在执行代码的机器上不同。编译器要评估像 (a + b) 这样的常量表达式,它需要获得与运行时相同的答案。

这对于 int 来说不是什么大问题——如果整数运算不同,您可以相对便宜地模拟整数运算。但是对于编译器来说,在目标设备上模拟浮点硬件可能非常困难。如果有不同版本的芯片并且编译器不知道代码将在哪个上运行,这甚至可能是不可能的。甚至在您开始弄乱 IEEE 舍入模式之前。因此该标准避免了对它的要求,因此它不必定义编译时评估何时以及如何与运行时评估不同。

正如 Brian 提到的,C++0x 将使用 constexpr 解决这个问题。如果我对最初动机的看法是正确的,那么大概 10 年的时间就足以克服指定这些东西的困难。

关于c++ - 为什么不允许 "inlined"静态常量,整数除外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1907214/

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