C++26: More function wrappers

https://lobste.rs/rss Hits: 16
Summary

C++26 continues to fill the gaps in our type-erased callable wrapper story. We already had std::function since C++11 and std::move_only_function since C++23, but there were still missing pieces. Now we’re getting two new additions: std::copyable_function and std::function_ref.What’s wrong with std::function?std::function has served us well, but it has two well-known issues. First, it can add significantly to binary size. Second, and more fundamentally, it has a const-correctness defect. Its operator() is declared const, but it can invoke a non-const operator() on the stored callable:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // https://godbolt.org/z/9YxcW5eqK #include <functional> #include <iostream> struct Counter { int counter = 0; void operator()() { ++counter; std::cout << "modifying state: " << counter << '\n'; } }; int main() { const std::function<void()> f = Counter{}; f(); // OK (!) } This defect is baked into the original design and cannot be fixed without breaking the ABI.C++23 introduced std::move_only_function (P0288R9) which fixed the const-correctness issue and added support for cv/ref/noexcept qualifiers. But as its name suggests, you can’t copy it. We still needed a wrapper that is both copyable and const-correct.std::copyable_functionP2548R6 fills exactly that gap. Its design follows std::move_only_function closely, adding a copy constructor and copy assignment operator, and requiring that stored callables are copy-constructible.The key difference from std::function is that the qualifier in the signature directly controls how operator() is declared:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // https://godbolt.org/z/orxPK9Gn9 #include <functional> struct Counter { int count = 0; int operator()() { return ++count; } // non-const }; int main() { // copyable_function<int()> means operator() is non-const std::copyable_function<int()> f = Counter{}; f(); // OK, non-const call // If you want const, you say so explicitly: // std::copyable_function<in...

First seen: 2026-05-20 15:41

Last seen: 2026-05-21 06:53