c++ - remove any element of vector<std::function<...>> that bound to member function -


how remove function bound member function of this object :

std::vector<std::function<void(int)>> callbacks;  class myclass { public:     myclass() {         callbacks.push_back(             std::bind(&myclass::myfunc,this,std::placeholders::_1)         );     }     ~myclass() {         auto = std::remove_if( std::begin(callbacks),                                   std::end(callbacks),                                   [&](std::function<void(int)>& f) {                 return // <-- question                        //     true (remove) if f bound member function                         //     of         });         callbacks.erase(it,std::end(callbacks));     }     void myfunc(int param){...} }; 

you can't in general case without buttload of work. type erasure clears information object, , std::function not expose information directly.

your specific example may have 1 member function candidate remove, class 5 members stored callbacks? you'll need test of them, , it's possible bind member functions using lambda, pretty undetectable.

here's 1 solution if:

  • all callbacks registered within myclass
  • the container amended store information
  • you're willing bookkeeping
std::vector<std::pair<std::function<void(int)>, void*>> callbacks;  class myclass{   static unsigned const num_possible_callbacks = 2; // keep updated   std::array<std::type_info const*, num_possible_callbacks> _infos;   unsigned _next_info;    // adds type_info , passes through   template<class t>   t const& add_info(t const& bound){     if(_next_info == num_possible_callbacks)       throw "oh shi...!"; // went out of sync     _infos[_next_info++] = &typeid(t);     return bound;   } public:   myclass() : _next_info(0){     using std::placeholders::_1;     callbacks.push_back(std::make_pair(         add_info(std::bind(&myclass::myfunc, this, _1)),         (void*)this));     callbacks.push_back(std::make_pair(         add_info([this](int i){ return myotherfunc(i, 0.5); }),         (void*)this));   }    ~myclass(){     using std::placeholders::_1;      callbacks.erase(std::remove_if(callbacks.begin(), callbacks.end(),         [&](std::pair<std::function<void(int)>, void*> const& p) -> bool{           if(p.second != (void*)this)             return false;           auto const& f = p.first;           for(unsigned = 0; < _infos.size(); ++i)             if(_infos[i] == &f.target_type())               return true;           return false;         }), callbacks.end());   }    void myfunc(int param){ /* ... */ }   void myotherfunc(int param1, double param2){ /* ... */ } }; 

live example on ideone.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -