Reputation: 1117
In my code I want to be able to do
Table<double> tbl;
tbl.Create(2, 2, 1.0, 2.0, 3.0, 4.0);
and via the constructor too
Table<double> tbl(2, 2, 1.0, 2.0, 3.0, 4.0);
From my experience the use of ellipses (...) leads to several hard to trace bugs, so I've come up with the following to initialize my table:
void Create(size_t rows, size_t columns, T val0)
{
ASSERT(rows * columns == 1);
Create(rows, columns);
_data[0] = val0;
}
void Create(size_t rows, size_t columns, T val0, T val1)
{
ASSERT(rows * columns == 2);
Create(rows, columns);
_data[0] = val0;
_data[1] = val1;
}
void Create(size_t rows, size_t columns, T val0, T val1, T val2)
{
ASSERT(rows * columns == 3);
Create(rows, columns);
_data[0] = val0;
_data[1] = val1;
_data[2] = val2;
}
I think you get the idea. However, this becomes rather annoying if I want functions for say up to 50 elements. Not to mention the fact I'll have to write all these constructors too. Isn't there another way to handle this more elegantly?
EDIT: Maybe I should explain why I don't want to use ellipses (...) in this case. Let's consider the following code:
Table<double> tbl(2, 2, 1.5, 2.1, 3, 4.5);
The compiler interprets the 5th argument as type int
and this is clearly not intended.
Upvotes: 0
Views: 191
Reputation: 477100
Variadic templates and initializer lists might work:
struct Table
{
std::vector<double> data;
template <typename ...Args>
Table(Args &&... args)
: data({std::forward<Args>(args)...})
{ }
};
Upvotes: 3