As a slight alternative to Ryan Haining's solution above, you don't actually need to put the array in a variable the line before:
#include <iostream>
struct A {
template<size_t N>
A(const int (&list)[N]) {
size = N;
myArr = new int[N];
int *tmp = myArr;
for(const int *i = list; i < list + N; ++i) {
*tmp++ = *i;
}
}
~A() {
delete[] myArr;
}
int *myArr;
size_t size;
};
int main(int argc, char **argv) {
A a = (int[]) {1, 2, 3, 4, 5};
for(int i = 0; i < a.size; ++i) {
std::cout << a.myArr[i] << std::endl;
}
return 0;
}
Because of copy elision and implicit constructors, you can get away with just a cast on the same line. The array is implicitly converted to your type, and then the temp value is moved to the stack dynamic storage efficiently through copy elision. This means revising your code would just require a couple of (type[])
and reworking your constructors to be array based instead of initializer_list based. Unfortunately, without c++11 foreach loops this can be a little annoying, but with some pointer works it's not awful, and you can always make some convenience macros like:
#define FOREACH(type, name, arr, N)\
for(type *__foreach__ptr__ = arr, (name) = *__foreach__ptr__;\
__foreach__ptr__ < (arr) + (N);\
++__foreach__ptr__, (name) = *__foreach__ptr__)
which would be used like:
int N = 5;
int arr[N] = {1, 2, 3, 4, 5};
FOREACH(int, val, arr, N) {
std::cout << val << std::endl;
}