How does the template parameter of std::function work? (implementation)

后端 未结 5 1230
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 08:45

In Bjarne Stroustrup\'s home page (C++11 FAQ):

struct X { int foo(int); };

std::function f;
f = &X::foo; //pointer to membe         


        
5条回答
  •  情书的邮戳
    2020-12-07 09:33

    How it does it (I believe) is left undefined (but I don't have a copy of the standard here).

    But given all the different possibilities that need to be covered I have the feeling that deciphering the exact definition of how it works would be really hard: So I am not going to try.

    But I think you would like to know how functors work and they are relatively simple. So here is a quick example.

    Functors:

    These are objects that act like functions.
    They are very useful in template code as they often allow you to use objects or functions interchangeably. The great thing about functors though is that they can hold state (a sort of poor man's closure).

    struct X
    {
         int operator()(int x) { return doStuff(x+1);}
         int doStuff(int x)    { return x+1;}
    };
    
    X   x;  // You can now use x like a function
    int  a = x(5);
    

    You can use the fact that functor hold state to hold things like parameters or the objects or the pointer to member methods (or any combination thereof).

    struct Y // Hold a member function pointer
    {
        int (X::*member)(int x);
        int operator(X* obj, int param) { return (obj->*member)(param);}
    };
    X  x;
    Y  y;
    y.member = &X::doStuff;
    int a = y(&x,5);
    

    Or even go further and bind parameters. So now all you need to provide is one of the parameters.

    struct Z
    {
        int (X::*member)(int x);
        int  param;
        Z(int (X::*m)(int), int p) : member(m), param(p) {}
    
        int operator()(X* obj)  { return (obj->*member)(param);}
        int operator()(X& obj)  { return (obj.*member)(param);}
    };
    
    Z z(&X::doStuff,5);
    
    X x;
    int a = z(x);
    

提交回复
热议问题