octavian octavian - 1 year ago 86
C++ Question

Overloaded pointer to function

I was looking over the following code:

string toUpper(string s) {
string result;
int (*toupperp)(int) = &toupper; // toupper is overloaded
transform(begin(s), end(s), back_inserter(result), toupperp);
return result;

I am confused by this line:

int (*toupperp)(int) = &toupper; // toupper is overloaded

1.Why is this line necessary?

2.I believe that
retrieves a pointer to something from memory. But
, the name of the function is already a pointer, no? Why can't we do this:

int (*toupperp)(int) = toupper;

3.Why is the function overloaded to
if it's used on a

Answer Source

1) It's not necessary, really. If you have used using namespace std directive, it's necessary to cast to the desired type to let the compiler know which overload you want. So, you might also say

transform(begin(s), end(s), back_inserter(result), static_cast<int(*)(int)>(&toupper));

Otherwise the following should be enough:

transform(begin(s), end(s), back_inserter(result), ::toupper);

2) Identifiers that are function names decay into pointers, yes, but they aren't exactly the same thing. That being said, in this case it should be fine to say

int (*toupperp)(int) = toupper;

or even (if you haven't used using namespace std directive):

auto toupperp = toupper; 

3) it's for compatibility with C standard library. It's used on every element of s, which for string is a char.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download