Блог пользователя omhari

Автор omhari, история, 2 года назад, По-английски

Is there any difference between normal function

Code

and a function created using std::function

Code
Теги c++
  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится +10 Проголосовать: не нравится

Yep -> Here

»
2 года назад, # |
Rev. 3   Проголосовать: нравится +11 Проголосовать: не нравится

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 года назад, # ^ |
      Проголосовать: нравится +9 Проголосовать: не нравится

    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 года назад, # ^ |
        Проголосовать: нравится +3 Проголосовать: не нравится

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

»
2 года назад, # |
Rev. 2   Проголосовать: нравится -11 Проголосовать: не нравится

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 года назад, # |
Rev. 2   Проголосовать: нравится +5 Проголосовать: не нравится

Yes, take an example:

First code
Second code, with the exactly same usage

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