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.
std::function
. The additionalcv-ref-noexcept
qualifiers are unnecessary instd::function
for the most part. You still haven't clarified why you need the function qualifiers, it seems unnecessary to me. – Jansenismstd::function
may throw an exception? How exactly requiring that theoperator ()
isnoexcept
is helpful here? – Jansenismstd::move_only_function
. – Jansenismnoexcept
callables would help. They'll just end up marking functionsnoexcept
regardless of possible exceptions, and perhaps file a bunch of bug reports for noreason just because code doesn't compile. – Jansenismstd::move_only_function
which is introduced in C++23... – Jansenism