【发布时间】:2017-05-11 21:34:13
【问题描述】:
在 C++11 中,是否有一种 DRY 方法来构造数组的所有元素,所有元素都具有相同的一组参数? (例如,通过单个初始化列表?)
例如:
class C {
public:
C() : C(0) {}
C(int x) : m_x{x} {}
int m_x;
};
// This would construct just the first object with a parameter of 1.
// For the second and third object the default ctor will be called.
C ar[3] {1};
// This would work but isn't DRY (in case I know I want all the elements in the array to be initialized with the same value.
C ar2[3] {1, 1, 1};
// This is DRYer but obviously still has repetition.
const int initVal = 1;
C ar3[3] {initVal, initVal, initVal};
我知道使用std::vector 可以轻松实现我的目标。我想知道原始数组是否也可以。
【问题讨论】:
-
也许是一个小助手模板?
-
你的默认构造函数是非常邪恶的。
-
取消它。
-
@Danra:为什么不委托:
C() : C(0) {}以公共术语记录默认构造函数。 -
完成,谢谢。 (也可以只做一个带有默认参数值的ctor,不想过多改变原问题的语义)
标签: c++ arrays c++11 constructor initializer-list