Search code examples
c++11constructorstd-function

std::function as a parameter in delegate constructor


I want to know why control does not go to AB() if I pass in abc(AB) into main() as control goes for initialization of i as 10 when abc(10) is passed

class abc
{
    int i;
        
    std::function<void(void)>func = nullptr;
public:
    abc(){}
        
    abc(std::function<void(void)>&fb):func(fb){}
    
    abc(int i):i(i){}
};

void AB()
{
    cout<< "fun_AB";
}

int main()
{
    abc(AB);
    abc(10);
}

Solution

  • abc(AB);
    

    This is a declaration of a variable of type abc named AB, equivalent to abc AB;. So the no-arg constructor is called. You could use this syntax if you don't want to name the variable:

    abc{AB};
    

    This "works" since it can't be parsed as a declaration, while your version can.

    But that's not enough, you need to change your constructor to accept a const&:

    abc(std::function<void(void)> const& fb) : func(fb)
    {
      func(); // if you want AB to be called
    }
    

    (Non-const reference won't bind to a temporary.)