C++23 introduces std::move_only_function which has support for const and l/r-value-reference on the implicit this parameter and noexcept(true/false) on the function itself.
The old std::function is lacking these overloads.
#include <functional>
int main(){
std::function<void()>([]noexcept(true){}); // okay ✓
std::function<void()>([]noexcept(false){}); // okay ✓
std::function<void()noexcept>([]noexcept(true){}); // not supported
std::function<void()noexcept>([]noexcept(false){}); // not supported
std::move_only_function<void()>([]noexcept(true){}); // okay ✓
std::move_only_function<void()>([]noexcept(false){}); // okay ✓
std::move_only_function<void()noexcept>([]noexcept(true){}); // okay ✓
std::move_only_function<void()noexcept>([]noexcept(false){}); // fails ✓
std::function<void()>([i=0]{}); // okay ✓
std::function<void()>([i=0]mutable{}); // okay ✓
std::function<void()const>([i=0]{}); // not supported
std::function<void()const>([i=0]mutable{}); // not supported
std::move_only_function<void()>([i=0]{}); // okay ✓
std::move_only_function<void()>([i=0]mutable{}); // okay ✓
std::move_only_function<void()const>([i=0]{}); // okay ✓
std::move_only_function<void()const>([i=0]mutable{}); // fails ✓
}
Unfortunately, as the name suggests, std::move_only_function cannot be copied.
#include <functional>
#include <vector>
int main(){
auto const fn = []{};
std::function<void()> a = fn;
std::vector<std::function<void()>> a_list{a, a};
std::move_only_function<void()> b = fn;
std::vector<std::move_only_function<void()>> b_list{b, b}; // error
}
Is there an analog function wrapper that supports copying? If this is not the case in C++23, is there a library that provides this?
I need a data type that is the owner of the function.
Is there an analog function wrapper that supports copying? If this is not the case in C++23, is there a library that provides this?
No.
In C++26 there will be std::copyable_function (P2548). There is a reference implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With