Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage and Syntax of std::function

It is necessary to me to use std::function but I don't know what the following syntax means.

std::function<void()> f_name = []() { FNAME(); };

What is the goal of using std::function? Is it to make a pointer to a function?

like image 752
user2982229 Avatar asked Dec 03 '13 14:12

user2982229


People also ask

What is std :: function used for C++?

C++ Library - <functional> 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.

Why do we need std :: function?

std::function can hold function objects (including lambdas), as well as function pointers with the correct signature. So it is more versatile.

What is std :: in C?

std is the namespace and by using :: (after the std) you explicitly using the functions of the namespace std. Now, imagine that you create your own namespace and some of the functions that you have created there have the same name as the functions in std namespace.

Is std :: function a function pointer?

No. One is a function pointer; the other is an object that serves as a wrapper around a function pointer. They pretty much represent the same thing, but std::function is far more powerful, allowing you to do make bindings and whatnot.


2 Answers

std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them. For std::function, the primary1 operations are copy/move, destruction, and 'invocation' with operator() -- the 'function like call operator'.

In less abstruse English, it means that std::function can contain almost any object that acts like a function pointer in how you call it.

The signature it supports goes inside the angle brackets: std::function<void()> takes zero arguments and returns nothing. std::function< double( int, int ) > takes two int arguments and returns double. In general, std::function supports storing any function-like object whose arguments can be converted-from its argument list, and whose return value can be converted-to its return value.

It is important to know that std::function and lambdas are different, if compatible, beasts.

The next part of the line is a lambda. This is new syntax in C++11 to add the ability to write simple function-like objects -- objects that can be invoked with (). Such objects can be type erased and stored in a std::function at the cost of some run time overhead.

[](){ code } in particular is a really simple lambda. It corresponds to this:

struct some_anonymous_type {
  some_anonymous_type() {}
  void operator()const{
    code
  }
};

an instance of the above simple pseudo-function type. An actual class like the above is "invented" by the compiler, with an implementation defined unique name (often including symbols that no user-defined type can contain) (I do not know if it is possible that you can follow the standard without inventing such a class, but every compiler I know of actually creates the class).

The full lambda syntax looks like:

[ capture_list ]( argument_list )
-> return_type optional_mutable
{
  code
}

But many parts can be omitted or left empty. The capture_list corresponds to both the constructor of the resulting anonymous type and its member variables, the argument_list the arguments of the operator(), and the return type the return type. The constructor of the lambda instance is also magically called when the instance is created with the capture_list.

[ capture_list ]( argument_list ) -> return_type { code }

basically becomes

struct some_anonymous_type {
  // capture_list turned into member variables
  some_anonymous_type( /* capture_list turned into arguments */ ):
    /* member variables initialized */
  {}
  return_type operator()( argument_list ) const {
    code
  }
};

Note that in c++20 template arguments were added to lambdas, and that isn't covered above.

[]<typename T>( std::vector<T> const& v ) { return v.size(); }

1 In addition, RTTI is stored (typeid), and the cast-back-to-original-type operation is included.

like image 107
Yakk - Adam Nevraumont Avatar answered Oct 07 '22 18:10

Yakk - Adam Nevraumont


Let's break the line apart:

std::function

This is a declaration for a function taking no parameters, and returning no value. If the function returned an int, it would look like this:

std::function<int()>

Likewise, if it took an int parameter as well:

std::function<int(int)>

I suspect your main confusion is the next part.

[]() { FNAME(); };

The [] part is called a capture clause. Here you put variables that are local to the declaration of your lambda, and that you want to be available within the lambda function itself. This is saying "I don't want anything to be captured". If this was within a class definition and you wanted the class to be available to the lambda, you might do:

[this]() { FNAME(); };

The next part, is the parameters being passed to the lambda, exactly the same as if it was a regular function. As mentioned earlier, std::function<void()> is a signature pointing to a method that takes no parameters, so this is empty also.

The rest of it is the body of the lambda itself, as if it was a regular function, which we can see just calls the function FNAME.

Another Example

Let's say you had the following signature, that is for something that can sum two numbers.

std::function<int(int, int)> sumFunc;

We could now declare a lambda thusly:

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

Not sure if you're using MSVC, but here's a link anyway to the lamda expression syntax:

http://msdn.microsoft.com/en-us/library/dd293603.aspx

like image 74
Moo-Juice Avatar answered Oct 07 '22 17:10

Moo-Juice