Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::bind in std::bind : compilation error (implicit cast) [duplicate]

When I want to create an std::function for wrapping work(..) member, I had a compilation error that tired me.

sample code :

class C{ 
public:
    C(){
        std::function<void(void) > f = std::bind(&C::work,
                                                 this,
                                                 std::bind(&C::step1, this),
                                                 std::bind(&C::step2, this));
        QList<decltype(f)> lst;
        lst.append(f);
        .....
    }
private:
    void work(std::function<bool()> fn1, std::function<bool()> fn2 ) {
        if (fn1()) {
            QTimer::singleShot(1, fn2);
        }
        else {
            QTimer::singleShot(5, fn1);
        }
    }

    bool step1(){return true;}
    bool step2(){return true;}
};

Compile Error:

main.cpp:49: erreur : conversion from 'std::_Bind_helper<false, void (C::*)(std::function<bool()>, std::function<bool()>), C* const, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)> >::type {aka std::_Bind<std::_Mem_fn<void (C::*)(std::function<bool()>, std::function<bool()>)>(C*, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>, std::_Bind<std::_Mem_fn<bool (C::*)()>(C*)>)>}' to non-scalar type 'std::function<void()>' requested
                                              std::bind(&C::step2, this));
                                                                        ^
like image 362
Mohamed Hamzaoui Avatar asked Mar 13 '23 04:03

Mohamed Hamzaoui


1 Answers

The problem is that bind() will eagerly evaluate nested bind expressions. So instead of ending up with some callable that returns bool (as you had intended from std::bind(&C::step1, this)), you just end up with bool.

Instead, use lambdas:

std::function<void(void) > f = [this]{
    work([this]{ return step1(); },
         [this]{ return step2(); });
};
like image 67
Barry Avatar answered Apr 26 '23 18:04

Barry