a concerned citizen a concerned citizen - 2 months ago 14
C++ Question

C++ Optional std::vector argument for function

I have seen some answers here, but they may not apply here. I have a (member) function that is mostly used with only one argument (the 1st):

const std::complex<double> Class::func(const std::complex<double> &x, \
std::vector<double> &y = 0, \
std::vector<double> &z = 0) const;


I would like for
y
and
z
to be optional, maybe even based on a fourth argument of type
string
, something like this:
func( , , , const std::string &choice)
, but which would let me only pass one argument to the function and the other two not be used. If I do pass
y
, for example, its declaration would have to be done previous of calling
func()
, same for
z
, but I'd like this to be optional, the function can be a bit heavy on the math side and there's no need to add the burden of calculating two additional vectors if they're not needed. Is this possible?

Nim Nim
Answer

Use pointers and pass a nullptr, check for this..

const std::complex<double> Class::func(const std::complex<double> &x, \
                                       std::vector<double> *y = nullptr, \
                                       std::vector<double> *z = nullptr) const;

I've defaulted them here, but that's optional...

Comments