c++ - 为什么来自常量 POD 对象的字段本身不是常量?

标签 c++ templates

我想为某个 GUID 专门化一个模板,它是一个 16 字节的结构。 GUID 对象有内部链接,所以我不能使用对象本身的地址,但我想我可以使用对象的内容,因为对象是一个常量。但这不起作用,如示例代码所示:

struct S
{
    int const i;
};
S const s = { 42 };
char arr[s.i];

如果 s 是常数,为什么 s.i 不是常数?任何解决方法?

最佳答案

struct s 的初始化可以在运行时发生。但是,数组的大小必须 在编译时已知。编译器(当然)不会知道 s.i 的值在编译时是已知的,所以它只会看到您正在将变量用于不应该的东西。问题不在于常量,而是何时需要数组大小的问题。

您可能误解了const 的含义。它仅表示变量初始化后,它永远不会更改。例如这是合法的:

void func(int x){
    const int i = x*5; //can't be known at compile-time, but still const
    //int array[i]; //<-- this would be illegal even though i is const 
}

int main(){
    int i;
    std::cin >> i;
    func(i);
    return 0;
}

为了绕过这个限制,在 C++11 中你可以将它标记为 constexpr 以指示该值可以在编译时确定。这似乎是你想要的。

struct S
{
    int const i;
};
int main(){
    constexpr S const s = { 42 };
    char arr[s.i];
    return 0;
}

编译:

$ c++ -std=c++11 -pedantic file.cpp


在 C99 中,你所做的是合法的,数组的大小不需要在编译时知道。

struct S
{
    int const i;
};
int main(){
    struct S const s = { 42 };
    char arr[s.i];
    return 0;
}

编译:

$ cc -std=c99 -pedantic file.c

关于c++ - 为什么来自常量 POD 对象的字段本身不是常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392553/

相关文章:

xcode - 创建 Xcode 项目模板需要了解什么?

c++ - 使用下标重载的单链表排序

c++ - 手动设置重载函数的优先级

javascript - Node.js Express 应用程序中的 Jade (1.0+) 模板错误 : 'Duplicate key "id"is not allowed. '

javascript - 构建 backbone.js 应用程序

c++ - 冲突的不匹配标签与标准库一起编译,但不以其他方式编译

c++ - 需要更有效的解决方案

c++ - 为什么无限循环?

c++ - C++中栈和堆的地址

c++ - Qt quint32 Little-Endianness with QDataStream