c++ overloading a function default argument

2019-07-26 14:08发布

问题:

I have a widely used c++ library which holds a method such as:

foo();

I want to overload this function to have a default argument such as:

foo(bool verbose=false);

does this change force me to recompile every code that uses this function? can't a call to foo() without the argument keep working as the no-args-signature didn't change?

by the way - I'm using gcc

thanks

回答1:

does this change force me to recompile every code that uses this function?

Yes, and the compile will fail, since there will be an ambiguity.

What you can do is overload the function like so:

foo(bool verbose);

and treat the case foo() as if the parameter was false.

This wouldn't require a re-compilation. You'd just have two functions:

foo() { foo(false); } //possibly
foo(bool verbose);

instead of one with a default paramter.



回答2:

If you mean you want to have both, then you can't as there's no way to know which you mean.

If you mean you want to replace foo() with foo(bool verbose=false) then it'll be a recompilation, as the calling code isn't really calling foo(), it's calling foo(false) with syntactic sugar hiding that.

You could though have:

someType foo(bool verbose)
{
  //real work here.
}
someType foo()
{
  return foo(false);
}

or if void:

void foo(bool verbose)
{
  //real work here.
}
void foo()
{
  foo(false);
}

Though if your earler foo() had been entirely in a header and inlinable, that's a different matter.