Skip to the content of the web site.

The functional library

These functions are found in the #include <functional> library.

The most useful feature of this library is the wrapper class std::function, and thus, you can require, for example, an argument to be real-valued function of a real variable by using the type:

     T my_function( std::function f, args... );

Then, the user is required to pass a function that has a signature that takes one argument of type double and returns a double, and then inside my_function(...), any time you call f( 3.4 ), the passed function is invoked. As another example, if you want an argument that is a bi-variate integer function returning a Boolean value, you would specify:

     T another_function( std::function g, args... );

Now, if you call g( 3, 4 ), the passed function will be called and return either true or false.

Next, the functional library has functional implementations of all of the operators, so the following are all equivalent as long as, for binary operators, the types of both operands are equal:

        m + n       std::plus( m, n )
        m - n       std::minus( m, n )
        m * n       std::multiplies( m, n )
        m / n       std::divides( m, n )
        m % n       std::modulus( m, n )
       -m           std::negate( m )

        m == n      std::equal_to( m, n )
        m != n      std::not_equal_to( m, n )
        m < n       std::less( m, n )
        m <= n      std::less_equal( m, n )
        m >= n      std::greater_equal( m, n )
        m > n       std::greater( m, n )
        m <=> n     std::compare_three_way( m, n )

        m && n      std::logical_and( m, n )
        m || n      std::logical_or( m, n )
       !m           std::logical_not( m )

        m & n       std::bit_and( m, n )
        m | n       std::bit_or( m, n )
        m ^ n       std::bit_xor( m, n )
       ~m           std::bit_not( m, n )

There are many other functions in this library, and you are welcome to investigate them, but we will describe only two more:

If you have a Boolean-valued function f, you can negate the result by writing a lambda expression: [f]( args... )->bool{ return !f( args... ); } or you can use this snippet of code:

     auto nf{ std::not_fn( f ) };
     // Now call nf( ... )...

If you know your arguments, but may choose a different function to call on those arguments, you can call a function using std::invoke(...) as follows:

     std::invoke( f, args... );
     std::invoke( g, args... );
     std::invoke( h, args... );