there is a question about overloading functions. 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 void fm(void(*fun)(int))
function you find that compiler can't statically overload function by pointer on function that accept parameter by value and pointer on function that accept const value. Also, if you uncomment void(*fun)(const int)
and comment void(*fun)(const int)
then all compiles sucessfully. But, if we using references it compiles OK. Don't get why, could you explain me please? Does this mean that pointers to function that accept parameter by value and by const value is same types?
UPD: Top-level const doesn't influence a function signature There is a good explanation why top-level const should be removed.
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.
(1) The use of same function name to create functions that perform a variety of different tasks is called as. function overloading. (2) Overloading refers to the use of same thing for different purposes. Function overloading or function. polymorphism, is an example of compile time polymorphism.
C++ lets you specify more than one function of the same name in the same scope. These functions are called overloaded functions, or overloads. Overloaded functions enable you to supply different semantics for a function, depending on the types and number of its arguments.
In PowerShell functions are not overloaded. The last definition overrides the previous in the same scope or hides the previous in a parent scope. Thus, you should create a single function and provide a way to distinguish its call mode by arguments.
Yes, top-level const will be just dropped. Error from gcc
redefinition of ‘void fm(void (*)(int))’
As you can see const is dropped.
Quote from N3376 8.3.5/5
After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.
Yes you cannot overload functions based on the const ness of a non pointer / non-reference argument, see: Functions with const arguments and Overloading
Which in turn implies that pointers to function that accept parameter by value and const value are same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With