简体   繁体   中英

c++ overloading a function default argument

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM