Home >Backend Development >C++ >Can You Take the Address of Standard Library Functions in C 20?
Consider the following code:
#include <cctype> #include <functional> #include <iostream> int main() { std::invoke(std::boolalpha, std::cout); // #1 using ctype_func = int(*)(int); char c = std::invoke(static_cast<ctype_func>(std::tolower), 'A'); // #2 std::cout << c << "\n"; }
In this code, there are two calls to std::invoke. Line #1 takes the address of std::boolalpha, while Line #2 attempts to do the same with std::tolower. The expected output is 'a'.
The question arises: is the expected output guaranteed in C 20? To answer this, we must delve into the concept of addressable functions.
According to [namespace.std], unless explicitly designated as addressable, attempting to obtain a pointer to a standard library function or its reference is undefined behavior (possibly ill-formed). This prohibition extends to forming a pointer-to-member for standard library non-static member functions.
Line #1:
std::boolalpha is designated as an addressable function by [fmtflags.manip]. This means that taking its address is well-formed, equivalent to std::cout.setf(std::ios_base::boolalpha).
Line #2:
Unfortunately, std::tolower is not explicitly designated as addressable in [cctype.syn]. Therefore, Line #2's attempt to take its address has undefined behavior (possibly ill-formed).
The expected output is not guaranteed. In fact, the code is not even guaranteed to compile due to the undefined behavior in Line #2.
This issue also applies to member functions. As [namespace.std] states, the behavior is undefined if a pointer is taken to a standard library member function.
The above is the detailed content of Can You Take the Address of Standard Library Functions in C 20?. For more information, please follow other related articles on the PHP Chinese website!