Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable number of float arguments

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 !

like image 631
e.farman Avatar asked Nov 15 '17 09:11

e.farman


People also ask

What is a variable number of arguments?

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.

How do you write a function with variable number of arguments in Python?

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.

Can a function have variable number of parameters justify?

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.)


1 Answers

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. };
}
like image 55
Jodocus Avatar answered Oct 16 '22 13:10

Jodocus