简体   繁体   English

c ++重载函数默认参数

[英]c++ overloading a function default argument

I have a widely used c++ library which holds a method such as: 我有一个广泛使用的c ++库,它包含如下方法:

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? 不能调用foo()而没有参数继续工作,因为no-args-signature没有改变?

by the way - I'm using gcc 顺便说一句 - 我正在使用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. 并将案例foo()视为参数为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. 如果你的意思是你想要用foo()替换foo() foo(bool verbose=false)那么它将是一个重新编译,因为调用代码并没有真正调用foo() ,它调用foo(false) ,语法糖隐藏了。

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. 虽然如果你的读者foo()完全处于标题中并且无法使用,那就是另一回事了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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