Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Okay…

By the way, why do we need std::function at all? Every time I saw it, it was to work around some dark corner of C++ type system or template dark magic.



Because function pointers in C++ carry no state. Given:

    class A { void foo(); };
    A a;
There is no such construct that lets you store a call to foo specialized for the instance 'a':

    ??? thing = a.foo; // doesn't exist
The only option in C++ is to take the address of the member function:

    &A::foo
But even this is not sufficient as it is equivalent to:

    void (*)(A * __this)
That is, the "this" pointer is not stored. Along comes mem_fun:

    struct mem_fun{ A *a; void(A::*ptr)(); };
Now you can store a call to foo for the instance a:

    mem_fun fun;
    fun.a = &a;
    fun.ptr = &A::foo;
Adding an operator() to mem_fun lets you treat a mem_fun instance as a function:

    void operator()(){ a->*ptr(); }

    ...
    fun()
Now, lets say you need to store this as a generic "callback". Well, how would you do that? Sure, you can store mem_fun instances but what about just plain function pointers? Now you can't store them. In comes std::function. With a little bit of VERY simple to understand magic, you can do:

    std::function<void()> foo = fun; // mem_fun
    std::function<void()> foo2 = global_fun; // simple member pointer


Most programming languages implicitly type erase closures, C++ does not. Type erasure can come at the cost of heap allocation and indirect function calls. If you need type erasure in C++ you can put any callable type inside std::function.


Is it because everyone was thrown by the syntax of function pointers (for no good reason, other than they never encountered them)?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: