Skip to content

Commit

Permalink
OEL_MEMBER_FN and OEL_MEMBER_VAR
Browse files Browse the repository at this point in the history
  • Loading branch information
OleErikPeistorpet committed May 7, 2024
1 parent 8a34d8b commit a8c2f3c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
38 changes: 38 additions & 0 deletions unit_test/util_gtest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,44 @@ TEST(utilTest, makeUnique)
a[i] = i;
}

TEST(utilTest, memberFn)
{
struct Moo
{
int noParam() const & { return -2; }

const int & twoParam(int & y, const int && z) && { return y += z; }
};

auto f = OEL_MEMBER_FN(noParam);
auto g = OEL_MEMBER_FN(twoParam);

Moo const x{};
EXPECT_EQ(-2, f(x));

auto y = 1;
EXPECT_EQ(3, g(Moo{}, y, 2));
using T = decltype( g(Moo{}, y, 2) );
static_assert(std::is_same_v<T, const int &>);
}

TEST(utilTest, memberVar)
{
struct Baz
{
int val;
} x{7};

auto f = OEL_MEMBER_VAR(val);

static_assert(std::is_same_v<decltype( f(x) ), int &>);

using T = decltype( f(static_cast<const Baz &&>(x)) );
static_assert(std::is_same_v<T, const int &&>);

EXPECT_EQ(7, f(x));
}

TEST(utilTest, toPointerContiguous)
{
using namespace oel;
Expand Down
15 changes: 15 additions & 0 deletions util.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@
* @brief Contains make_unique_for_overwrite, as_signed/as_unsigned, index_valid, ssize and more
*/


/** @brief Take the name of a member function and wrap it in a stateless function object
*
* `wrapped(object, args)` becomes the same as `object.func(args)`.
* This macro works for function templates and overload sets, unlike std::mem_fn.
* Note that passing a function or pointer to member often optimizes worse. */
#define OEL_MEMBER_FN(func) \
[](auto && ob_, auto &&... args_) -> decltype(auto) \
{ return decltype(ob_)(ob_).func(decltype(args_)(args_)...); }

//! Take the name of a member variable and wrap it in a stateless function object
#define OEL_MEMBER_VAR(var) \
[](auto && ob_) noexcept -> auto && { return decltype(ob_)(ob_).var; }


namespace oel
{

Expand Down

0 comments on commit a8c2f3c

Please sign in to comment.