c++ overloading a function default argument

£可爱£侵袭症+ 提交于 2019-12-11 06:49:13

问题


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.



来源:https://stackoverflow.com/questions/12160993/c-overloading-a-function-default-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!