Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a copyable function wrapper in C++23 with support for const/ref/noexcept?

Tags:

c++

c++23

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.

like image 279
Benjamin Buch Avatar asked Jun 25 '26 18:06

Benjamin Buch


1 Answers

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.

like image 172
Barry Avatar answered Jun 28 '26 10:06

Barry