C ++类可以包含一个静态const std :: array在头文件中内联初始化吗? [英] Can a C++ class contain a static const std::array initialized inline in a header file?

查看:384
本文介绍了C ++类可以包含一个静态const std :: array在头文件中内联初始化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我得到的:

struct Foo
{
   static std::array<double, 4> acgt_default_background_frequencies() { return {0.281774, 0.222020, 0.228876, 0.267330}; }
};

但我更喜欢不使用函数一个变量,如下:

But I'd prefer to not use a function and instead just have a variable, like this:

struct Foo
{
   static constexpr std::array<double, 4> acgt_default_background_frequencies = {0.281774, 0.222020, 0.228876, 0.267330};
};

我想要编译,但是当我尝试使用 Foo :: acgt_default_background_frequencies 它会给链接器错误未定义的引用`Foo :: acgt_default_background_frequencies'。

What I want compiles, but when I try to use Foo::acgt_default_background_frequencies it gives the linker error "undefined reference to `Foo::acgt_default_background_frequencies'".

我想做的是什么?我认为读者对我的头部更清楚,如果我有值内联作为一个常量比隐藏它在.cpp文件,并有一个常数,而不是一个函数也看起来更清楚。是不是constexpr的点允许这样的东西?如果不可能,为什么不?

Is what I am trying to do possible? I think it is clearer to the reader of my header if I have the value inlined as a const than to hide it in the .cpp file and having a constant as opposed to a function also seems clearer. Isn't the point of constexpr to allow stuff like this? If it isn't possible, why not?

推荐答案

em>一个 static 数据成员,它有一个初始化器,但是你没有在任何地方提供定义。如果您 odr-use

What you have in the second example is a declaration of a static data member which has an initializer, but you haven't provided a definition anywhere. If you make odr-use of that member, a definition will be required.

要提供定义,请将以下内容添加到.cpp文件中。

To provide a definition, add the following to your .cpp file

constexpr std::array<double, 4> Foo::acgt_default_background_frequencies;

问题的声明在C ++ 14中有效,但请注意,在C ++ 11中需要一组额外的花括号,例如

The declaration in the question works in C++14, but note that in C++11 you need an extra set of curly braces, e.g.

struct Foo
{
  static constexpr std::array<double, AlphabetSize> acgt_default_background_frequencies = {{0.281774, 0.222020, 0.228876, 0.267330}};
};

相关标准从N3337 §9.4.2/ 3 [class.static.data]

The relevant standardese from N3337 §9.4.2/3 [class.static.data]


... A static 文字类型的资料成员在类定义中使用 constexpr 说明符声明;如果是,其声明应指定括号或初始值,其中每个 initializer-clause 常数表达式。 ...如果在程序中使用odr(3.2),并且命名空间范围定义不包含初始化器,则成员仍然在命名空间范围中定义。

... A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. ... The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

这篇关于C ++类可以包含一个静态const std :: array在头文件中内联初始化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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