class元素的数组为静态constexpr成员 [英] array of class element as a static constexpr member
问题描述
我有一个类的constexpr静态成员的引导问题酒吧
这是酒吧
本身就是一个数组。请看下面的完全正确的code:
I have a bootstrap problem with a constexpr static member of a class Bar
which is an array of Bar
itself. Consider the following perfectly correct code:
struct Foo {
int i;
static const std::array<Foo, 2> A;
};
const std::array<Foo, 2> Foo::A {{{1},{2}}};
现在我想有富:: A
不仅是常量,而且 constexpr
。我面
这个问题是静态constexpr成员初始化必须做
里面的 的类的声明。然而,由于申报还没有完成,
编译器还不知道实例的大小,因此拒绝
使该阵列。例如:
Now I'd like to have Foo::A
not only const but also constexpr
. I'm faced
with the problem that static constexpr member initialization must be done
inside the class declaration. However, since the declaration is not yet finished,
the compiler doesn't yet know the size of an instance and therefore refuse to
make the array. For example
struct Bar {
int i;
constexpr static const std::array<Bar, 2> A{{{1},{2}}};
};
时,拒绝与
/usr/include/c++/4.8/array: In instantiation of ‘struct std::array<Bar, 2ul>’:
ess.cpp:14:56: required from here
/usr/include/c++/4.8/array:97:56: error: ‘std::array<_Tp, _Nm>::_M_elems’ has incomplete type
typename _AT_Type::_Type _M_elems;
有没有解决办法?或替代方法?
Is there a way to solve that ? Or a workaround ?
推荐答案
我已经找到了以下解决方案,确保
I've found the following solution which ensure that
- 数组计算在编译时间
- 该数组存储在该结构而不被复制。
我们的想法是一个constexpr阵列上使用const引用。
The idea is to use a const reference on a constexpr array.
struct Bar {
int i;
static const std::array<Bar, 2> &A;
};
constexpr const std::array<Bar, 2> BarA {{{1},{2}}};
const std::array<Bar, 2> &Bar::A = BarA;
这篇关于class元素的数组为静态constexpr成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!