Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting a function to a function type that is identical except for return type fail? [duplicate]

Tags:

c++

Possible Duplicate:
Is the return type part of the function signature?

Following up on a related but tangential question ( How to disambiguate function templates that differ only by return type? ), I would like to ask a question related to the fact that the return type of a function is not considered to be part of the signature of a function.

Consider the following code:

#include <iostream>

int foo()
{
    return 0;
}

int main()
{
    long n = static_cast<long(&)()>(foo)(); // Error: incorrect return type
    int p = static_cast<int(&)()>(foo)(); // Compiles just fine 
}

The line of code noted above results in a compilation error, because the return type of the function type to which foo is being cast does not match the return type of the function foo.

But I thought the return type of a function does not play a role in the signature of the function!

According to a certain line of thinking, since the function signature long(&)() matches the signature of foo, the cast of foo to a function of this type should succeed.

However, the cast does not succeed. Where does the reasoning go wrong? If the cast cannot fail due to the function signature, then why does the cast fail?

like image 401
Dan Nissenbaum Avatar asked Jan 26 '26 03:01

Dan Nissenbaum


1 Answers

You're correct that the return type doesn't form part the signature of the function.

However, it does form part of the type of the function, and you're not allowed to convert pointers to incompatible function types.

like image 124
Mike Seymour Avatar answered Jan 28 '26 16:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!