Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default value of const reference parameter

Currently I have two functions:

void foo(const A & a) {
  ...
  result = ...
  result += handle(a); // 1
  bar(result);
}

void foo() {
  ...
  result = ...
  bar(result);
}

All code in foo() are the same except 1.

Can I merge them to one function like following?

void foo(const A & a = 0) {
  ...
  ...
  if (a) result += handle(a); // this won't work, but can I do something similar?
  bar(result);
}

Btw, the parameter has to be a reference as I would like to keep the interface unchanged.

like image 833
Deqing Avatar asked Nov 05 '25 17:11

Deqing


1 Answers

You can use the Null Object Pattern.

namespace
{
  const A NULL_A; // (possibly "extern")
}

void foo(const A & a = NULL_A) {
  ...
  result = ...
  if (&a != &NULL_A) result += handle(a);
  bar(result);
}
like image 83
Drew Dormann Avatar answered Nov 07 '25 07:11

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!