Casting to a specific function overload

See these two overloads of a function F :-

void F()
    cout << "F()" << endl;

void F(int i = 10)
    cout << "F(int) " << i << endl;

Now if you attempt to call the function as F() you’ll get a compiler error.

F(); <- C2668: 'F' : ambiguous call to overloaded function

The right way to do this would be :-

((void (*)(void))F)();
((void (*)(int = 10))F)();

Looks beautiful, doesn’t it? C++ syntax is truly the most beautiful among all programming languages!

Posted in C++

9 thoughts on “Casting to a specific function overload

  1. I think you should redefine your definition of beauty. This is the problem with C++ syntax, it’s too complicated.

  2. Hello
    Shouldn’t the compiler understand the difference? or am I confusing
    this with something else?!!! isn’t this polymorphism?

  3. Hi,

    This seems to be interesting… how compiler resolves the ambiguity… Still, even if this
    compiles… Which function will get called for F()…

    Thanks –

  4. Nish, the only reason you are getting an error here is that the declaration “void F()” resolves to “void F(int)” for non-member functions. This is a legacy ferature for C compatibility, and one which PC-Lint will warn you about if you run code written this way through it.

    By the way, another thing that will result in a PC-Lint message (#1924, assuming your warning policy has it enabled) is the use of C-style casts as you’ve advocated.

    Effective C++” discusses why (although I would hope it would be self evident). I *always* use C++ style casts rather than C style casts in new code as a result.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s