我可以像这样使用函数重载吗:
#include <iostream>
void foo(...)
{
std::cout << "::foo(...) \n";
}
void foo(int)
{
std::cout << "::foo(int) \n";
}
int main()
{
foo(0);
foo('A');
foo("str");
foo(0, 1);
}
什么标准涉及到这个?在什么情况下会使用::foo(...)?
我可以像这样使用函数重载吗:
#include <iostream>
void foo(...)
{
std::cout << "::foo(...) \n";
}
void foo(int)
{
std::cout << "::foo(int) \n";
}
int main()
{
foo(0);
foo('A');
foo("str");
foo(0, 1);
}
void foo(int)
该函数接受一个类型为int
的参数。
void foo(...)
该函数接受任意数量、任意类型的参数。当调用没有单个int
参数时,将选择它。总的来说,它并不是非常有用。
另请注意,向...
传递类类型对象是未定义行为。
在N3337中,我可以看到:
13.3.2可行函数
如果候选函数的参数少于m个,则只有在其参数列表中含有省略号(8.3.5)时,它才是可行的。对于重载解析,任何没有对应参数的参数都被认为“匹配省略号”(13.3.3.1.3)。
当你以以下方式声明一个函数:
void foo (...)
这意味着foo接受任意数量的参数。
因此,当这个函数是最合适的时候,它将被调用。
在你的情况下,每当你不写:
foo(//Some single int).
foo(0) //Calls foo(int).
foo('A) //Calls foo (int). as you can convert a char to an int.
foo("str") //Calls foo(...) . as you can not convert a string to an int.
foo(1,2) //Calls foo(...) . as this is the only possible function
cause the second foo function only takes one int.
void foo(...)
将接受可变参数。当没有提供与其他同名函数的参数列表匹配的参数或类型时,它将被调用。
foo(0); //This will call void foo(int) function
foo('A'); //This will call void foo(int) function
foo("str"); //This will call void foo(...) function
foo(0, 1); //This will call void foo(...) function
注意:
虽然省略号在函数重载中可以正常工作,但并不建议追求可变参数函数。除非您在C++方面有更丰富的经验以了解其中的陷阱。我建议仅在try catch块中使用它,因为在某些情况下无法预测错误。