lefticus / cpp_weekly

The official C++ Weekly Repository. Code samples and notes of future / past episodes will land here at various times. PR's will be accepted in some cases.
The Unlicense
663 stars 24 forks source link

taking address of STL functions #385

Closed billyzs closed 2 weeks ago

billyzs commented 1 month ago

Channel

C++Weekly

Topics In some cases one may be tempted to directly take the address of an STL function instead of writing a seemingly redundant wrapper:

// suppose I have some integers that needs to be stringified:
std::vector<int> v{1,2,3,4,5};
std::vector<std::string> vv(v.size());

std::transform(
    v.begin(), v.end(), vv.begin(),
    [](int x){ return std::to_string(x); }
    // or can I replace my own lambda with this instead? 
    // static_cast<std::string(*)(int)>(std::to_string)
);

Alas, aside from a few designated addressable functions (since C++20) mostly related to IO manipulation, the standard specifies that taking the address of STL functions, or member functions of STL containers, is UB and possibly ill formed.

Related readings: https://stackoverflow.com/a/55687045 https://akrzemi1.wordpress.com/2018/07/07/functions-in-std/ (for what's an "overload set" and defensive programming against STL changes)

Length bite-sized (5-10 minutes)

lefticus commented 1 month ago

Maybe "How To Pass Template Functions and Function Overloads To Other Functions"

lefticus commented 2 weeks ago

Here's some options: https://compiler-explorer.com/z/MEve5EEEd

lefticus commented 2 weeks ago

Coming in Ep437