I have a polymorphic method hierarchy like this:
void func(double x, const std::string& s) = 0;
and I want to pass an "optional" argument which is modified within the method:
void func(double x, const std::string& s, uint64_t& i = 0) = 0;
but I receive errors that my reference was not initialised.
What is the best way to implement the above?
uint64_t& is an L-Value reference, and can therefore not bind to an R-Value, like the literal you provide as default argument. You must provide an L-Value as default.
One option is to define a dummy object that you pass as default, e.g.:
static uint64_t dummy_default_value = 0;
void func(double x, const std::string& s, uint64_t& i = dummy_default_value ) = 0;
I would avoid default parameter for virtual method (see good-practice-default-arguments-for-pure-virtual-method), so just add an extra overload
virtual void func(double x, const std::string& s, uint64_t& i) = 0;
void func(double x, const std::string& s) { int i; func(x, s, i) };
If you really want to keep default argument, you may use boost::optional:
virtual void func(double x,
const std::string& s,
boost::optional<uint64_t&> i = boost::none) = 0;
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