Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a complex C style type casting expression work?

Tags:

c++

casting

I was looking for a way to uppercase a standard string. The answer that I found included the following code:

int main()
{
    // explicit cast needed to resolve ambiguity
    std::transform(myString.begin(), myString.end(), myString.begin(),
      (int(*)(int)) std::toupper)
}

Can someone explain the casting expression “(int(*) (int))”? All of the other casting examples and descriptions that I’ve found only use simple type casting expressions.

like image 325
MF Dinosaur Avatar asked Jul 01 '26 02:07

MF Dinosaur


2 Answers

It's actually a simple typecast - but to a function-pointer type.

std::toupper comes in two flavours. One takes int and returns int; the other takes int and const locale& and returns int. In this case, it's the first one that's wanted, but the compiler wouldn't normally have any way of knowing that.

(int(*)(int)) is a cast to a function pointer that takes int (right-hand portion) and returns int (left-hand portion). Only the first version of toupper can be cast like that, so it disambiguates for the compiler.

like image 92
Chowlett Avatar answered Jul 04 '26 03:07

Chowlett


(int(*)(int)) is the name of a function pointer type. The function returns (int), is a function *, and takes an (int) argument.

like image 43
perreal Avatar answered Jul 04 '26 02:07

perreal