• Register
100 points
5 1

Std::function c++

posted May 12 2 min read

While writing code using C++ programming, you probably use function pointers and function objects to solve problems and perform calculations, when you use C++ templetes(Standard library).

Std::function is class template usually known as general purpose polymorphic wrapper.It behaves like a function pointer if we define in simple language.Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

 Syntax:

std::function<void()>

This returns nothing and takes no arguments to pass into this and pointing to method which returns nothing.

std::function< double( float, float ) >

Here it takes two arguments as float datatype and return the result in double.

From C++11 standards,they add lambda which add the ability to write simple function-like objects -- objects that can be invoked with ().The simple syntax of lambda is [](){code}.There is a difference in std::function and lambda.

Full Syntax of Lambda:

[ capture_list ]( argument_list )// you can refer cppreference.com
-> return_type optional_mutable
{
  code
}

Here,[] is capture list which includes  variables that are local to the declaration of lambda and you want these variable to be in lambda function itself.Like: you want to use x=4 as variable so use [=](){sum();}.

  • [=] means capture any referenced variable by making a copy.
  • [&] means capture any referenced variable by reference.

Example1:

First,you use class templete that will subtract two numbers.
std::function<int(int, int)> sumLambda;

Now you can declare lamba like this:

sumLambda = [ ](int a, int b) { return a + b; };

Example2:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    auto subLambda=[](int a,int b){return a-b;};
    cout<<"Subtraction of two integers:"<<subLambda(7,2)<<endl;

    return 0;
}

Output

Subtraction of two integers:5

 

1 Comment

Very helpful post. Thanks