Skip to content

Commit

Permalink
[ufunction] allow bind to copies of src funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
iboB committed Sep 24, 2024
1 parent 998ae90 commit d51231a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
7 changes: 4 additions & 3 deletions include/itlib/ufunction.hpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// itlib-ufunction v1.01
// itlib-ufunction v1.02
//
// Unique Function
// Non-copyable and noexcept move-constructible replacement for std::function
Expand Down Expand Up @@ -30,6 +30,7 @@
//
// VERSION HISTORY
//
// 1.02 (2024-09-24) Allow binding to copies of source functions as per C++23
// 1.01 (2022-09-23) Allow ufunction from a free function
// 1.00 (2020-10-15) Initial release
//
Expand Down Expand Up @@ -88,10 +89,10 @@ class ufunction : private std::function<F>
ufunction& operator=(ufunction&&) noexcept = default;

template <typename FO>
ufunction(FO&& f) noexcept : function(copy_wrapper<FO>{std::move(f)}) {}
ufunction(FO f) noexcept : function(copy_wrapper<FO>{std::move(f)}) {}

template <typename FO>
ufunction& operator=(FO&& f) noexcept
ufunction& operator=(FO f) noexcept
{
function::operator=(copy_wrapper<FO>{std::move(f)});
return *this;
Expand Down
14 changes: 13 additions & 1 deletion test/t-ufunction-11.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

TEST_SUITE_BEGIN("ufunction");

static_assert(!std::is_copy_constructible<itlib::ufunction<void()>>::value, "must not be copy constructible");
static_assert(!std::is_copy_assignable<itlib::ufunction<void()>>::value, "must not be copy assignable");

struct fnocopy
{
fnocopy() = default;
Expand All @@ -22,7 +25,7 @@ struct fnocopy
other.owner = false;
return *this;
}
int operator()(int n) { return n+5;}
int operator()(int n) { return n+5; }

bool owner = true;
};
Expand Down Expand Up @@ -52,3 +55,12 @@ TEST_CASE("Free func")
func = sum;
CHECK(func(3, 4) == 7);
}

TEST_CASE("from copy")
{
auto func = [](int a, int b) { return a + b; };
itlib::ufunction<int(int, int)> f(func);
itlib::ufunction<int(int, int)> f2(func);
CHECK(f(1, 2) == 3);
CHECK(f2(10, 20) == 30);
}
6 changes: 2 additions & 4 deletions test/t-ufunction-14.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ TEST_CASE("Basic")
{
using namespace itlib;

auto uptr = std::make_unique<int>(53);
ufunction<void()> func([u = std::move(uptr)](){
ufunction<void()> func([u = std::make_unique<int>(53)](){
CHECK(*u == 53);
});
func();

auto uptr2 = std::make_unique<int>(102);
func = [u = std::move(uptr2)]() {
func = [u = std::make_unique<int>(102)]() {
CHECK(*u == 102);
};
func();
Expand Down

0 comments on commit d51231a

Please sign in to comment.