Using a function std :: or a link to a transfer as an input parameter to an object of a called general purpose object of a higher order function?

I was interested to learn the main differences, pros and cons in writing a higher-order function, as an input parameter, std::functionor forwarding link, for example. template<typename F> void hof(F&& fun);. Obviously, the former is more stringent than the latter in that it defines the type of function to which the input called object should correspond.

+4
source share
2 answers

std::functionhas many advantages, but it also has a series of cons that you should consider.
As an example:

  • .
    , :

    #include <functional>
    #include <utility>
    #include <memory>
    
    template<typename F>
    void func(F &&f) { std::forward<F>(f)(); }
    
    int main() {
        func([ptr = std::make_unique<int>()](){});
    }
    

    :

    #include <functional>
    #include <utility>
    #include <memory>
    
    void func(std::function<void(void)> f) { f(); }
    
    int main() {
        func([ptr = std::make_unique<int>()](){});
    }
    
  • ( ):

    , , , f target - , -.

    , , , .

  • std::function, bad_alloc.

  • ... , , , .

std::function , , .
, -, , std::function. , , , std::function.
, , .

+3

std::function . template std::function .

- (Y-combinator vs std::function) . std::function 3,5 , Y-combinator. , , std::function , template.

gcc.godbolt.org, .


:

#if defined(STDFN)
void pass_by_stdfn(std::function<void()> f)
{
    f();
}
#else
template <typename TF>
void pass_by_template(TF&& f)
{
    f();
}
#endif

volatile int state = 0;

int main()
{
#if defined(STDFN)
   pass_by_stdfn([i = 10]{ state = i; });
#else
   pass_by_template([i = 10]{ state = i; });  
#endif
}

STDFN , :

main:
        mov     DWORD PTR state[rip], 10
        xor     eax, eax
        ret
state:
        .zero   4

STDFN , 48 .

+4

Source: https://habr.com/ru/post/1662830/


All Articles