I have a template class like this:
template <unsigned N>
class Pixel {
float color[N];
}
I hope to have a constructor with exact N
parameters to initialize the array in the class, like this:
Pixel<N> (float x_1, float x_2, ..., float x_N) {
color[0] = x_1;
color[1] = x_2;
...
}
Obviously I can't implement the constructor by hand for each N
. So how can I achieve this goal by template metaprogramming or any other techniques?
The other answers are good and practical, but the question is interesting, and the technique behind doing something like that can form a good basis for similar, but more complicated and/or practical problems and solutions. Here's something that counts the constructor arguments the way you describe:
template <unsigned int N>
class Pixel {
public:
template<typename... Floats> //can't use float... anyway
Pixel(Floats&&... floats) : color{std::forward<Floats>(floats)...} {
static_assert(sizeof...(Floats) == N, "You must provide N arguments.");
}
private:
float color[N];
};
int main() {
Pixel<3> p(3.4f, 5.6f, 8.f);
Pixel<3> p2(1.2f); //static_assert fired
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With