In standard c++ we can write :
int myArray[5] = {12, 54, 95, 1, 56};
I would like to write the same thing with a template :
Yet another solution which doesn't need adder
class template. Now you can do this:
int main() {
Array<int, 10> array;
array = 1,2,3,4,5,6,7,8,9,10;
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Here is the complete solution: http://www.ideone.com/I0L1C
You're right. This is not possible with current standard C++. However, with the next standard (c++0x) initializer-lists will do just that!
My solution is to write a class template that accumulates all the values which get passed to the constructor. Here is how you can initizalize your Array
now:
Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
The implementation of adder
is shown below with complete demonstration:
template<typename T>
struct adder
{
std::vector<T> items;
adder(const T &item) { items.push_back(item); }
adder& operator,(const T & item) { items.push_back(item); return *this; }
};
template <class Type, size_t N>
class Array
{
public:
Array(const adder<Type> & init)
{
for ( size_t i = 0 ; i < N ; i++ )
{
if ( i < init.items.size() )
m_Array[i] = init.items[i];
}
}
size_t Size() const { return N; }
Type & operator[](size_t i) { return m_Array[i]; }
const Type & operator[](size_t i) const { return m_Array[i]; }
private:
Type m_Array[N];
};
int main() {
Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
for (size_t i = 0 ; i < array.Size() ; i++ )
std::cout << array[i] << std::endl;
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
See the online demo at ideone yourself : http://www.ideone.com/KEbTR
This becomes possible in C++0x using initializer lists. Currently, there is no way to do this.
The closest you can get without this is to use Boost.Assign.
It's actually very trivial; just remove the constructors and make the data members public. The template issue is a red hering; the same rules apply as for any class: if it is an aggregate, you can use aggregate initialization; if it's not, you can't.
-- James Kanze