【发布时间】:2014-01-24 19:39:14
【问题描述】:
当元素类型没有默认构造函数时,有没有办法构造一个包含所有重复元素的模板化元素数组?
我尝试了以下方法:
template<typename T, int n> struct Array {
template<typename... Args> explicit Array(const T& arg1, Args... args)
: m_a{arg1, args...} { }
static Array<T,n> all(const T& value) {
Array<T,n> ar; // error: use of deleted function 'Array<TypeWithoutDefault, 10>::Array()'
for (int i=0; i<n; i++)
ar.m_a[i] = value;
return ar;
}
T m_a[n];
};
struct TypeWithoutDefault {
TypeWithoutDefault(int i) : m_i(i) { }
int m_i;
};
int main() {
// works fine
Array<TypeWithoutDefault,2> ar1 { TypeWithoutDefault{1}, TypeWithoutDefault{2} };
(void)ar1;
// I want to construct an Array of n elements all with the same value.
// However, the elements do not have a default constructor.
Array<TypeWithoutDefault,10> ar2 = Array<TypeWithoutDefault, 10>::all(TypeWithoutDefault(1));
(void)ar2;
return 0;
}
【问题讨论】:
-
好吧,您需要
repeat功能。看看我的回答:How to initialize std::array<T, n> elegantly if T is not default constructible? -
让我知道这是否也适合您。如果没有,我会修改它,并将其作为答案发布。
-
谢谢,不幸的是,正如几个人指出的那样,我的问题是重复的。 @Nawaz 和 @Jarod42 的回答都非常合适。
index_sequence和make_index_sequence的简洁结构非常好。
标签: c++ arrays templates c++11 initialization