General Utilities

Overview
Function Objects or Functors are widely used in std library and serve in various modes such as passing ref objects, wrapping up function objects, accessing member functions etc. 

Details
Functors
A functor is an object or structure that can be called like a function by overloading the function call operator () .  Functors also wrap a state during construction which can be used in function calls.
The following shows a functor implementation.
struct Greet
{
    void operator()()
    {
        time_t curr_time;
	curr_time = time(NULL);

        tm *tm_local = localtime(&curr_time);
        size_t h = tm_local->tm_hour;
        cout << "Hello, ";

        if (h > 4 && h < 12)
            cout << "Good Morning";
        else if (h > 11 && h < 17)
            cout << "Good Afternoon";
        else if (h > 16 )
            cout << "Good Evening";
        cout << "!" << endl;
    }        
} g;

//Example
g(); //prints @ 2 am : Hello, Good Evening!
This is depicted in this example.

lambda expression➹
A functor or function objects is an object or structure that can be called like a function by overloading the function call.

Predefined function objects
The standard library provides the following template based predefined functors. 
The standard library also provides a specialization for each of the classes below with return type and parameters deduced. 

For example, both the following adds two numbers.
template<typename T> plus;
template<typename T=void> plus;

Both can be used as below.
//returns 12
plus<int>{}(10,2);

//returns 12
plus<>{}(10,2);

Note these predefined functors can  also be used in algorithms such as accumulate() as predicates.

arithmetic operations
NameDescriptionExample
plusAddition
//returns 12
plus{}(10,2);
minusSubtraction
//returns 8
minus{}(10,2)
modulusModulo
//returns 0
modulus{}(10,2); 
multipliesMultiplication
//returns 20
multiplies{}(10,2); 
dividesDivision
//returns 5
divides{}(10,2);
negateNegate
//returns -10
negate{}(10);

Relational Operations
NameDescriptionExample
equal_toequality comparison
//returns false
equal_to{}(10,2);
not_equal_tonon-equality comparison
//returns false 
not_equal_to{}(10,2); 
greatergreater-than inequality comparison
//returns true
greater{}(10.2);
greater_equalgreater-than-or-equal-to comparison
//returns true
greater_equal{}(10,2);
lessless-than inequality comparison
//returns false
less{}(10,2);
less_equalless-than-or-equal-to comparison
//returns false
less_equal{}(10,2); 

bitwise Operations
NameDescriptionExample
bit_andBitwise AND
//returns 0x0c
bit_and{}(0xff,0x0c); 
bit_orBitwise OR
//returns 0xfc
bit_or{}(0xf0,0x0c); 
bit_xorBitwise XOR
//returns 0xf3
bit_xor{}(0xff,0x0c);
bit_notBitwise NOT
//returns 0xffff0000
bit_not{}(0xffff);

logical Operations
NameDescriptionExample
logical_andLogical AND
//returns false
logical_and{}(true,false);  
logical_notLogical NOT
//returns false
logical_not{}(true);
logical_orLogical OR
//returns true
logical_or{}(true,false);
logical_notLogicalNOT
//returns false
logical_not{}(true);
This is depicted in this example 6

function and class member pointers
function pointers are pointers to functions that can be defined as variables. function pointer can be defined for "C" type free functions as shown below.
void print(int) {}

    void (*fp)(int) = &print;
    fp(8); //calls print(8);

function pointers can be also defined for members of a class such as fields and functions. However it's not possible to directly assign from an instance of a class. Therefore operators ->* and .* are used exclusively to call functions or access fields of a class as shown below. Notice that function call requires extra parenthesis.
struct Msg
{
    char buf[50];
    void print(){cout << buf;};
} m{};


    char  (Msg::*buf)[50]    = &Msg::buf;
    void (Msg::*fp)()   = &Msg::print;
    strcpy(m.*buf,"hello, world"); //same as m.buf or (&m)->buf
    (m.*fp)(); // same as m.print() or ((&m)->*fp)()

reference_wrapper is a class template that wraps a reference in a copyable, assignable object.
It creates a wrapper around a reference to object or reference to function of type T. Instances of reference_wrapper are objects but they are implicitly convertible to T&, so that they can be used as arguments with the functions that take the underlying type by reference.
Helper functions ref and cref are often used to generate reference_wrapper objects.
reference_wrapper is used to pass objects by reference to bind, the constructor of thread, or the helper functions make_pair and make_tuple. It can also be used as a mechanism to store references inside standard containers (like vector) that cannot normally hold references.

A helper function that constructs an object of the appropriate reference_wrapper type to hold a reference to elem.

A helper function that constructs an object of the appropriate reference_wrapper type to hold a const reference to elem.

The function wrapper classes provide alternative to function pointers. It's basically a  general-purpose polymorphic function wrapper. Instances of function classes can store, copy, and invoke function pointers, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

placeholder namespace➹
This namespace defines an unspecified number of objects: _1_2_3,..._N, where _N is implementation specific upper limit. 

is_placeholder trait class can be used to check if the argument is a placeholder type or not.
Function template mem_fn generates wrapper objects for pointers to members, which can store, copy, and invoke a pointer to member. Both references and pointers (including smart pointers) to an object can be used when invoking a mem_fn.

Returns a function object based on fn, but with its arguments bound to args.

Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers.

This template supplies a uniform interface for allocator types.

Summary of Examples
NameDescriptiongithubwandbox
Example    Generic Functorsource    outputsource + output
Example 2Lambda - Capture and mutablesource    output source + output
Example 3Lambda - Parameterssource    outputsource + output
Example 4Lambda - Trailing return typesource    outputsource + output 
Example 5Lambda - in Actionsource    outputsource + output
Example 6Predefined functorssource    outputsource + output
Example 7functionsource    outputsource + output
Example 8reference_wrappersource    outputsource + output
Example 9ref and crefsource    outputsource + output
Example 10mem_fnsource    outputsource + output
Example 11bind - simplesource    outputsource + output
Example 12bind - complexsource    outputsource + output
Example 13allocator - Usagesource    outputsource + output
Example 14Shared memory based custom allocator (windows)source    outputsource + output

No comments:

Post a Comment