1

I was reading this answer: https://stackoverflow.com/a/5539302/588867

What is going on with this part: (int (*)(int))tolower in this line of code:

transform(s.begin(),s.end(),s.begin(),(int (*)(int))tolower );

If I make this function and the code works:

int myToLower(int c){
    return tolower(c);
}

transform(s.begin(),s.end(),s.begin(), myToLower);

What's plain English about this part: (int (*)(int)).

JeJo
  • 30,635
  • 6
  • 49
  • 88
biocyberman
  • 5,675
  • 8
  • 38
  • 50

1 Answers1

2

You can see this answered in my answer, that's a function pointer. You can read more about them here: http://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions

Fundamentally this is a pointer to a function that takes in an int argument and returns an int.


The reason the transform works when using myToLower and not with an uncast tolower, is that in code is that the tolower function is overloaded in the std namespace by both the locale library's tolower and the ctype library's tolower. When only the function name is used as an uncast pointer no overload resolution is performed, and you'll get an error. When you cast the function pointer you're telling the compiler which overload you want.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • I checked the cppreference page you gave. I can understand this: `void (*p2)(int) = f`. But from that to `(int (*)(int))tolower`, there are two steps involved: 1. definine an anonymous function pointer type `(int (*)(int))` and 2. cast `tolower` to that type. Is that correct? – biocyberman May 17 '18 at 11:51
  • 2
    Yes, cast directly says compiler which of overloaded functions we want to use. I would use static_cast<> BTW. – Spock77 May 17 '18 at 13:26