omhari's blog

By omhari, history, 2 years ago, In English

Is there any difference between normal function

Code

and a function created using std::function

Code
Tags c++
  • Vote: I like it
  • +5
  • Vote: I do not like it

»
2 years ago, # |
  Vote: I like it +10 Vote: I do not like it

Yep -> Here

»
2 years ago, # |
Rev. 3   Vote: I like it +11 Vote: I do not like it

So i've extensively and exclusively used std::function for a long time (not anymore, for the reasons ill state) and this is what i have to say:

  • The main advantage of std::function over regular functions is that you cam make functions that use variables inside the scope youre in. It's a lot of times, very unpractical to create helper functions that make use of variables or arrays inside the code, and creating it inside the main function is valuable in those situations

  • The main problem with std::function is that its slow (specially if the ammount of captures you use is large) and replaceable by lambda functions (they have the same declaration, except with auto instead of std::function).

  • Lambdas are faster and a lot of the times more practical. The only problem with them is that recursion is iffy, you need to pass the own function as paremeter, however with std::function you need to include the parameters and return type in the typename, which is equally annoying.

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    IMO you don't ever need std::function in competitive programming. Whenever you want to pass a function as a parameter to another function, use auto (C++20) or template functions (before C++20), or if you're passing it to a constructor, use a template class.

    Regarding your last point, both approaches have some flaws, but in my experience auto self is shorter and of course it doesn't have any overhead.

    • »
      »
      »
      2 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Agreed. Reading again i see i didnt make it clear that i switched for lambdas (now its editted)

»
2 years ago, # |
Rev. 2   Vote: I like it -11 Vote: I do not like it

if you are one who doesn't like self passing shit in lambdas but at the same time hate typing signature for std:: function I recommend this short define:

#define fun(T, name, ...) function<T(__VA_ARGS__)> name = [&](__VA_ARGS__)->T

and just code like usual function:

fun(void, dfs, int v, int p) {
    //body
};

P. S. I know about slowness and about y_combinator

  • »
    »
    2 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    oh, someone explain me this downvote mania

  • »
    »
    2 years ago, # ^ |
    Rev. 2   Vote: I like it -8 Vote: I do not like it
    Alternative
»
2 years ago, # |
Rev. 2   Vote: I like it +5 Vote: I do not like it

Yes, take an example:

First code
Second code, with the exactly same usage

You don't really need global variables when using std::functions.