Home >Backend Development >C++ >Can You Take the Address of Standard Library Functions in C 20?

Can You Take the Address of Standard Library Functions in C 20?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 02:54:18543browse

Can You Take the Address of Standard Library Functions in C  20?

Can Addresses of Standard Library Functions Be Taken?

Background

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'.

Addressable Functions

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.

Analysis

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).

Conclusion

The expected output is not guaranteed. In fact, the code is not even guaranteed to compile due to the undefined behavior in Line #2.

Addressable Member Functions

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn