定义constexpr静态数据成员 [英] Defining constexpr static data members

查看:85
本文介绍了定义constexpr静态数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我知道在C ++中,静态成员可以在类内部进行初始化,前提是它们是const文字类型,如下所示

So, I'm aware that in C++ static members can be initialized inside the class if they are a const literal type like the following

class test{
public:
        static constexpr int stc = 1;
private:
        int a = 0;
        int b = 0;
        int c = 0;
};

和静态constexpr变量 stc 可以是在编译器可以直接替换成员值的地方使用,即

and the static constexpr variable stc can be used where the compiler can directly substitute the value of the member i.e

int main () {int array[test::stc];}  

但是,如果在不能直接由编译器替换值的上下文中使用:

However, if used in a context where the value cannot be directly substituted by the compiler:

int main() { const int &cs = test::stc; } 

然后编译器(c)生成错误

then the compiler (clang) generates an error

c++ -std=c++11 -pedantic    t.cpp   -o t
Undefined symbols for architecture x86_64:
  "test::stc", referenced from:
      _main in t-a8ee2a.o
ld: symbol(s) not found for architecture x86_64

除非在类外定义了静态成员,否则:

unless the static member is defined outside the class like so:

constexpr int test :: stc;

为什么会这样?

推荐答案

int main() { const int &cs = test::stc; } 

test :: stc 是odr-在

int main () {int array[test::stc];}  

不是。

以下示例来自 C ++ 11标准支持上述想法。

The following example from the C++11 Standard supports the above idea.


struct S { static const int x = 0; };
const int &f(const int &r);  
int n = b ? (1, S::x)    // S​::​x is not odr-used here
          : f(S::x);     // S​::​x is odr-used here, so a definition is required


从实际的角度来看, cs 将是无效的引用,除非 test :: stc 有地址。另一方面, array 只需要 test :: stc 的值,可以在编译时对其进行评估。 array 不需要有效的对象 test :: stc 的地址。

Looking at it from practical point of view, cs will be an invalid reference unless test::stc has an address. array, on the other hand, needs just the value of test::stc, which can be evaluated at compile time. array does not need the address of test::stc to be a valid object.

在程序中必须对一次使用过的对象进行一次定义。

An object that is odr-used must be defined exactly once in a program.

这篇关于定义constexpr静态数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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