【发布时间】:2018-12-02 12:57:11
【问题描述】:
我想初始化我的数组项,同时避免不必要的实例和副本(类似于这个问题:initialize std::array without copying/moving elements)。
初始化列表确实适用于少量对象。
我想通过代码 sn-p 来执行此操作,因为我的数组有数百个项目...
我该怎么做?
#include <array>
#include <iostream>
class mytype {
public:
int a;
mytype() : a(0) {}
mytype(int a) : a(a) {}
};
int main() {
// explict constructor calls to instantiate objects does work
std::array<mytype, 2> a = { { mytype(10), mytype(20) } };
std::cout << a[0].a; // 10
// I want to do something like this - what does not work of course
std::array<mytype, 2> b = { { for (i = 0, i++, i < 2) mtype(10 * i); } };
}
【问题讨论】:
-
@πάνταῥεῖ THX + 是的,看起来相关并且确实解释了为什么
for循环不是编译时表达式。但是构造函数初始化的解决方案是什么样的呢? -
使用递归模板即可。
-
@πάνταῥεῖ THX,我明白了(对于一个简单的问题,该死的聪明但复杂的解决方案;-)
标签: c++ initialization c++14 stdarray