I'm trying to implement a flexible constructor for my struct Polynomial :
struct Polynomial
{
std::vector<float> coefficients;
size_t degree;
};
The degree of the polynomial is variable. What I would like is to have a constructor like
Polynomial(float... _coefficients);
I've tried variadic template :
template<float... Args>
Polynomial(Args... args);
But float is a non-type, so I've done :
template<typename... Args>
Polynomial(Args... args);
But this allow my coefficients to be anything, not realy what I want. I know I could use :
Polynomial(size_t _degree, ...);
But it is really unsafe.
At the moment I'm using :
Polynomial(std::vector<float>);
But this force the call to be like :
Polynomial P({f1, f2, f3}); // with fn floats
So I would like to know if there is a good way to do this.
Thank you !
To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
Before Java SE 5.0, every Java method had a fixed number of parameters. However, it is now possible to provide methods that can be called with a variable number of parameters. (These are sometimes called "varargs" methods.)
You can use initializer_list
:
#include <vector>
#include <initializer_list>
struct Polynomial {
std::vector<float> coeffs;
std::size_t degree;
Polynomial(std::initializer_list<float> init)
: coeffs{ init }, degree(init.size()) { }
};
int main() {
Polynomial p{ 1, 2, 3. };
}
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