Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ number of function's parameters fixed by template parameter [duplicate]

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?

like image 577
Oliver Q Avatar asked Dec 12 '22 13:12

Oliver Q


1 Answers

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
}
like image 179
chris Avatar answered Dec 14 '22 01:12

chris