What I mean is, for example, a constructor for a class like the following:
class vector<size_t N, typename FLOAT=double> {
vector(FLOAT ...x) {} // I want exactly N arguments here
};
I hope it's clear that I do not want a variadic function, but a function that takes exactly N arguments, when N is known at compile-time. Thus, using the example above, vector<3>(1.5, 2.5)
should produce a compile-time error, while vector<2>(1.5, 2.5)
should compile and run.
Is this possible?
I was thinking that perhaps this could be done with parameter packs, but I'm not quite sure how.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.
Function TemplateFunction overloading can take varying numbers of arguments.
Function Templates with Multiple ParametersYou can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.
With some indirection, you may do something like:
template <std::size_t, typename T> using alwaysT = T;
template <typename FLOAT, typename Seq> struct vector_impl;
template <typename FLOAT, std::size_t... Is>
struct vector_impl<FLOAT, std::index_sequence<Is...>> {
vector_impl(alwaysT<Is, FLOAT>... floats) { /*...*/}
};
template <std::size_t N, typename FLOAT>
using vector = vector_impl<FLOAT, std::make_index_sequence<N>>;
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