Is there a way to construct a templated array of elements with all duplicate elements when the element type does not have a default constructor?
I tried the following:
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;
}