6

Can i actually use a function overloading like this:

#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);
}

What standard says about it? And in what kind of situations i'll get ::foo(...)?

0

4 Answers 4

3
void foo(int)

will accept one argument of type int.

void foo(...)

accepts any number of arguments, of any type. It will be selected when the call doesn't have a single int argument. Not very useful, in general.

Also note that it is undefined behavior to pass objects of class type to ....

2
  • 1
    Non-POD class types, that is. (C++11 express this requirement in terms of triviality and changes UB to conditionally-supported implementation defined behaviour.)
    – Luc Danton
    Sep 15, 2012 at 11:00
  • conditionally-supported implementation defined behaviour sounds even worse to me. :-) Looks a lot like Don't do it!.
    – Bo Persson
    Sep 15, 2012 at 13:34
2

In N3337 I can see:-

13.3.2 Viable functions
A candidate function having fewer than m parameters is viable only if it has an ellipsis in its parameter list (8.3.5). For the purposes of overload resolution, any argument for which there is no corresponding parameter is considered to “match the ellipsis” (13.3.3.1.3) .

0

When you declare a function in the following way :

  void foo (...) 

this mean foo accepts any number of arguments.

So this function will be called when this is the must suitable one.

In your case whenever you won't write :

foo(//Some single int).

In your specific main, this will happen :

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.
0

void foo(...) will take variable arguments. And it will be called when there the no or type of argument does not match the provided argument list of other function with the same function name.

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

NOTE:

Although the ellipsis works fine with function overloading, it is not highly recommend pursuing variadic functions. At least not until you have significantly more experience in C++ to understand the pitfalls. I would suggest its use only with the try catch block where there are situations when the error cannot be predicted.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.