Function Pointer Conversion Restriction

I wonder why a static_cast from int (*)(const int&) for type int (*)(int&) is illegal. If I have a pointer to a function that technically allows int& to be accepted, but wants to assign it a function that voluntarily refuses permission to change the specified value, should it not behave like a special case of a function that could in principle?

In other words, given that I can pass an arbitrary function int& to int (*)(const int&) , is there a deeper reason in the standard why the latter cannot be considered a special case of int (*)(int&) and such a variable is assigned?

M (! W) E :

 int g(const int& q) { return q; } int main() { int (*f)(int&) = static_cast<int(*)(int&)>(g); // breaks int x = 1; return f(x); } 
+7
c ++ casting language-lawyer
source share
1 answer

[...] there is a deeper reason in the standard why [...]

These questions are usually impossible to answer. Maybe no one thought of it as a useful thing to look into. C ++ generally has limited support for covariance and contravariance. There are many other safe conversions that are potentially possible, not just link qualifications.

For example, a function pointer, such as Animal*(*)(Dog*) , can be initialized from both Animal*(*)(Animal*) and Dog*(*)(Dog*) . But today, support is not supported.

So the real answer is probably: write a sentence .


However, in this case, we can still achieve the desired behavior through a clearly underestimated rule: almost always lambda. We know, by name, the function we want to use and lambdas without capture (which we don't need) can be converted to function pointers:

 int (*f)(int&) = [](int& i) { return g(i); }; 
+5
source share

All Articles