为什么不是来自常量POD对象常量的字段本身? [英] Why aren't fields from constant POD object constants themselves?

查看:99
本文介绍了为什么不是来自常量POD对象常量的字段本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to specialize a template for a certain GUID, which is a 16 byte struct. The GUID object has internal linkage, so I can't use the address of the object itself, but I thought I could use the contents of the object, since the object was a constant. But this doesn't work, as illustrated by this example code:

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

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

Why isn't s.i a constant if s is? Any workaround?

推荐答案

struct s 运行。但是,在编译时必须知道数组的大小编译器不会(肯定)知道 si 的值在编译时是已知的,所以它只是看到你正在使用一个变量,你不应该是。

The initialization of the struct s can happen at run time. However, the size of an array must be known at compile time. The compiler won't (for sure) know that the value of s.i is known at compile time, so it just sees you're using a variable for something you shouldn't be. The issue isn't with constness, it's an issue of when the size of the array is needed.

你可能会误解什么 const code>表示。它只意味着在变量初始化之后,它永远不会改变。例如这是合法的:

You may be misunderstanding what const means. It only means that after the variable is initialized, it is never changed. For example this is legal:

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 ,以指示该值可以在编译时确定。这似乎是你想要的。


To get around this limitation, in C++11 you can mark it as constexpr to indicate that the value can be determined at compile time. This seems to be what you want.

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中,你所做的是合法的,数组的大小在编译时不需要知道。

in C99, what you're doing is legal, the size of an array does not need to be known at compile time.

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

编译:

$ cc -std = c99 -pedantic file.c

这篇关于为什么不是来自常量POD对象常量的字段本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆