A lot here depends on where you're starting from (C++03 vs. C++11) and where you really want to go (passing just numbers, or if passing something like an std::array
works for you).
If you have C++11 and you just want to pass the numbers, it's probably easiest to do something like:
#include <vector>
#include <iostream>
#include <initializer_list>
class pixel {
std::vector<double> color;
public:
pixel(std::initializer_list<double> && l) : color(l) {}
~pixel() {
// show the data we received:
for (double const &f : color)
std::cout << f << "\t";
}
};
int main() {
pixel{1.9, 2.8, 3.7, 4.6, 5.5};
}
Note that an std::initializer_list
doesn't support narrowing conversions, so if you want to store the numbers as float
instead of double
, you'll need to actually pass float
s:
pixel{1.9f, 2.8f, 3.7f, 4.6f, 5.5f};
Unlike @Chris's solution, however, this does not attempt to enforce passing a given number of arguments -- it just conforms to storing whatever number you pass. In return for that, it's a bit easier to use. You don't need to specify the size -- it figures that out from the number of items you pass.
If you like that general idea, but insist on an array and C++03 (why?) you can do something like this:
#include <vector>
#include <iostream>
#include <algorithm>
template<class T, size_t N>
class pixel {
T color[N];
public:
pixel(T(&matrix)[N]) {
std::copy_n(matrix, N, color);
}
};
template <class T, size_t N>
pixel<T, N> make_pixel(T(&matrix)[N]) {
return pixel<T, N>(matrix);
}
int main() {
float a [] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
pixel<float, 5> p = make_pixel(a);
return 0;
}
In this case, I've passed float
as a template parameter, but if you're really sure it'll always be float
, you can just pass the size, and use float
instead of T
.