我想将 Foo
类中的 static const std::vector
初始化为 {0, 1, 2, 3, ..., n
其中 n
在编译时根据下面 enum
中的 Last
的值已知。 Foo::all
的目标是包含 Fruit
枚举的所有值。
在foo.h
中:
enum Fruit { Apple, Orange, Banana, ..., Last };
class Foo {
public:
static const vector<int> all;
};
在foo.cpp
中:
// initialization of Foo::all goes here.
最佳答案
作为第三种选择:
namespace {
std::vector<int> create();
}
const std::vector<int> Foo::all = create();
和create()
可以为所欲为,甚至可以使用 push_back()
对于每个元素,因为 vector
它创建的不是 const。
或者你可以制作create()
一个constexpr
功能使用 <index_tuple.h>
#include <redi/index_tuple.h>
namespace {
template<unsigned... I>
constexpr std::initializer_list<int>
create(redi::index_tuple<I...>)
{
return { I... };
}
}
const std::vector<int> Foo::all = create(typename redi::make_index_tuple<Last>::type());
关于C++动态初始化常量静态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14105485/