FrozenHeart
FrozenHeart

Reputation: 20756

Function overloading with ellipsis

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(...)?

Upvotes: 6

Views: 1861

Answers (4)

heretolearn
heretolearn

Reputation: 6555

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.

Upvotes: 0

user1655481
user1655481

Reputation: 376

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

Upvotes: 2

oopsi
oopsi

Reputation: 2039

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.

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92341

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

Upvotes: 3

Related Questions