functional
function
Overview
estd::function
provides a set of predefined class templates for function
objects. estd::function
objects are objects specifically designed
to be used with a syntax similar to that of functions. Instances of
estd::function
can store, copy, and invoke any callable target functions,
lambda expressions, bind expressions, or other function objects, as well as
pointer to member functions of a class.
Usage
The usage guidelines apply for function:
Usage guidance |
The estd::function is used as a function pointer hence it should always be initialized to appropriate function or estd::none to avoid undefined behavior. |
Example
The following example shows a simple example of the usage of a
estd::function
with a function:
/* Define a zero parameter function */
int32_t foo0() { return 2; }
TEST(Function, TestFreeFunctionZeroParams)
{
::estd::function<int32_t()> f = ::estd::function<int32_t()>::create<&foo0>();
ASSERT_EQ(2, f());
}
The next example shows a simple example of the usage of a estd::function
with a functor:
/* Define functor */
struct Bar0
{
int32_t operator()() const { return 7; }
};
TEST(Function, TestFunctorZeroParams)
{
Bar0 bar;
::estd::function<int32_t()> f(::estd::make_function(bar));
ASSERT_EQ(7, f());
}
The next example shows a simple example of the usage of a estd::function
with a lambda function:
auto callme = [](::estd::function<int32_t()> f) { return f(); };
auto f = []() { return 88; };
ASSERT_EQ(88, callme(::estd::make_function(f)));
closure
Introduction
estd::closure
provides functions which are used to bind a function or a
member function with arguments. It creates a new function object by
“binding” a function or member function to a specific object or value, allowing
it to be called with a different number of arguments.
Usage
The usage guidelines apply for closure:
Usage guidance |
The estd::closure can be used with functions having maximum of five arguments. |
Example
The following example shows a simple example of the usage of a
estd::closure
estd::bind_all
:
int32_t foo3(float, int32_t, int32_t h) { return h; }
TEST(Function, TestFreeFunctionClosureThreeParam)
{
::estd::function<int32_t(float, int32_t, int32_t)> f
= ::estd::function<int32_t(float, int32_t, int32_t)>::create<&foo3>();
::estd::closure<int32_t(float, int32_t, int32_t)> d
= ::estd::bind_all(f, 2.14f, int32_t(3), int32_t(4));
ASSERT_EQ(4, d());
}
The next example shows a simple example of the usage of a
estd::closure
estd::bind1st
:
int32_t foobar3(int32_t const, int32_t const, int32_t const h) { return h; }
TEST(Function, TestBind1stThreeParams)
{
using fct = ::estd::function<int32_t(int32_t const, int32_t const, int32_t const)>;
fct f = fct::create<&foobar3>();
using bnd = ::estd::binder1st<int32_t(int32_t const, int32_t const, int32_t const)>;
bnd g = ::estd::bind1st(f, int32_t(23));
ASSERT_EQ(4, g(2, 4));
}