简体   繁体   中英

Alternative to taking the address of a standard library function / possibly ill-formed behaviour

issue: possibly ill-formed behaviour by taking the address of a standard library function... see example below. therefore, im looking for an alternative to taking the address of a standard library function.

according to http://eel.is/c++draft/namespace.std#6 and as noted by @Caleth in Why function-pointer assignment work in direct assignment but not in conditional operator

"Note that you are relying on unspecified (possibly ill-formed) behaviour by taking the address of a standard library function (that isn't designated addressable)"

As in this example:

int (*fun)(int) = std::toupper;
int t = fun('x');

my questions:

1) is there no safe way to call (in this example) toupper by pointer?

2) does a static_cast make the function pointer to a std lib function safe? like:

int (*fun)(int) = static_cast<int(*)(int)>(std::toupper);
int t = fun('x');

2) Is there another way to achieve the below functionality via a single function with signature "int fun(int)"

bool choice = true;
int (*fun)(int);

if (choice) {
    fun = std::toupper;
}
else {
    fun = std::tolower;
}

int t = fun('x');

is there no safe way to call (in this example) toupper by pointer?

Not directly, only through one level of indirection (see below).

does a static_cast make the function pointer to a std lib function safe?

No. It can nail down an overload set to one particular function signature, but this doesn't have anything to do with whether you're allowed to take the address of that function.

Is there another way to achieve the below functionality via a single function with signature int fun(int)

There is an alternative, you can wrap the function call in two lambdas. This requires little change to the original snippet:

bool choice = true;
int (*fun)(int);

if (choice)
    fun = [](int ch){ return std::toupper(ch); };
else
    fun = [](int ch){ return std::tolower(ch); };

int t = fun('x');

This works nicely because both lambdas have no state and the same signature, so they implicitly convert to the function pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM