C++是否可以超载一个函数,以便其参数分别接受文字和参考?
我在使用C ++过载方面有问题,并且想知道是否有人可以提供帮助。
我正在尝试超负荷功能,以便其参数分别接受参考和文字。
例如,我想超载func1
和func2
to func
:
int func1 (int literal);
int func2 (int &reference);
我想在这种情况下使用func
:
func(3); // call func1
int val = 3;
func(val); // I want func2 to be called, but ambiguous error
有什么方法可以超载这些功能?
谢谢!任何帮助将不胜感激! 对不起,英语不好。
I'm having a problem with using C++ overloading and was wondering if anybody could help.
I'm trying to overload functions so that its argument accept reference and literal respectively.
For example, I want to overload func1
and func2
to func
:
int func1 (int literal);
int func2 (int &reference);
and I want to use func
in this situations:
func(3); // call func1
int val = 3;
func(val); // I want func2 to be called, but ambiguous error
Is there any way to overload these functions?
thanks! Any help would be appreciated!
sorry for poor english.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文字和临时值只能作为const引用传递,而命名值则可以在可用的情况下使用非const参考。您可以将其与
&
或&&
一起创建2个过载。有关原因和更多详细信息,请阅读 rvalues” prvalues 。
下面的代码显示了最常见的情况将使用哪种函数过载,第一个是您询问的函数:
输出:输出:
Literals and temporary values can only be passed as const references while named values will prefer a non-const reference if available. You can use this with either
&
or&&
to create the 2 overloads.For why and more details read up on rvalues, lvalues, xvalues, glvalues and prvalues.
The code below shows which function overload will be used for the most common cases, the first 2 being the ones you asked about:
Output: