Function overloading function pointer

the question is about overload functions. Take a look at this code:

#include<iostream> void fv(int){} void fc(const int){} void fvr(int&){} void fcr(const int&){} void fm(void(*fun)(const int)) { std::cout << "Constant called" << std::endl; } //void fm(void(*fun)(int)) //{ // std::cout << "non Constant called" << std::endl; //} void fm(void(*fun)(const int&)) { std::cout << "Constant ref called" << std::endl; } void fm(void(*fun)(int&)) { std::cout << "non Constant ref called" << std::endl; } int main() { fm(&fc); fm(&fv); fm(&fvr); fm(&fcr); return 0; } 

If you uncomment the function void fm(void(*fun)(int)) , you will find that the compiler cannot statically overload the function with a pointer to a function that takes a parameter by value and a pointer to a function that takes a value const. In addition, if you uncomment void(*fun)(const int) and the comment void(*fun)(const int) , then everything compiles successfully. But, if we use links, it compiles OK. Do not understand why, could you please explain to me? Does this mean that function pointers that take a parameter by value and the value of const are the same?

UPD: The top-level constant does not affect the signature of the function. There is a good explanation of why const-const should be removed.

+6
source share
2 answers

Yes, the top level const will simply be removed. Gcc error

override "void fm (void (*) (int))

As you can see, const is disabled.

Quote from N3376 8.3.5 / 5

After creating a list of parameter types, any top level cv-qualifiers that change the parameter type are deleted when the function type is formed.

+3
source

Yes, you cannot overload functions based on the constant argument of non pointer / non-reference, see Functions with const arguments and overloading

Which, in turn, implies that function pointers that take a parameter by value and constant are of the same type.

+2
source

Source: https://habr.com/ru/post/984001/


All Articles