【发布时间】:2016-08-16 12:29:08
【问题描述】:
我有一些容器struct,其中包含一组配置元素。
struct config
{
const std::vector<int> config_items;
const std::vector<double> another_items;
}
另外,我有一个“容器容器”,它应该包含这些配置容器的已知且有限数量的实例(例如 3 个)。每个config 实例在对应的vectors 中应该有不同的ints 和doubles。
struct setup
{
const std::vector<config> items;
}
所有vectors 的项目都应该是const,因为它们应该被定义一次并且永远不会改变。
由于vectors 是const,我只能在构造函数初始化列表中初始化它们。但我希望有多个具有不同值的实例。
我可以创建一些子 structs 来创建子构造函数中的每个配置。但这不起作用,因为我无法在子构造函数中初始化父成员:
struct config_1 : public config
{
config_1() : config_items { 1, 2 }, another_items { 1.0, 2.0 } {} // Doesn't work
}
这似乎也是一个非常糟糕的决定(删除const,复制...):
struct config
{
std::vector<int> config_items;
std::vector<double> another_items;
}
struct setup
{
std::vector<config> items;
}
void init()
{
config c;
c.config_items = { 1, 2 };
c.another_items = { 1.0, 2.0 };
setup s;
s.items = { c };
}
我也不能创建一个初始化列表构造函数,因为我有多个vectors:
struct config
{
config(std::initializer_list<int> i, std::initializer_list<double> d); // No go
std::vector<int> config_items;
std::vector<double> another_items;
}
背景:我想为我的嵌入式应用程序提供一个硬编码的const 配置结构(可能放在数据部分甚至闪存中)。无需从任何配置文件等中读取内容。
所以我的问题是:你会建议我如何创建这样一个const 配置容器?
编辑
std::vectors 在这里实际上是错误的。我正在使用一个自定义容器来保存实例中的数据,例如 std::array,而不是像 std::vector 那样在堆上分配存储空间。
所以环境应该是这样的:
struct config
{
const std::array<int, 2> config_items;
const std::array<double, 2> another_items;
}
struct setup
{
const std::array<config, 3> items;
}
【问题讨论】:
-
[FYI] 向量是动态的,因此需要在运行时进行初始化。如果你想要静态数据,那么你应该考虑使用
std::array。 -
@NathanOliver,感谢您的建议。
vectors 在这里只是为了简单起见,我们使用的是我们自己的模板化容器和内部数据存储。
标签: c++ c++11 initialization constants