Std :: vector from std :: functions find

I have a vector filled with callback functions, and I would like to check if the function callback already exists before adding it. I do not know if it will work even until it even compiles.

vector<std::function<void(void*)>> _callbacks; void Event::RegisterCallback(std::function<void(void*)> callback) { if (callback == NULL) return; vector<std::function<void(void*)>>::iterator it = std::find(_callbacks.begin(), _callbacks.end(), callback); if (it == _callbacks.end()) { _callbacks.push_back(callback); } else { //print error throw; } } 

This gives a compilation error: "Overload resolution selected by the remote operator" == "in alorithm (805). This is due to the call to the search function.

How do I get this to work, and will it really properly compare function calls with the same method?

thanks

+7
c ++ c ++ 11
source share
2 answers

As noted in the comments, the simplest solution is to use C-style default function pointers, since they support the == operator as opposed to the C ++ 11 function , which does not.

 using func_type = void(*)(); vector<func_type> _callbacks; void Event::RegisterCallback(func_type callback) { if (callback == nullptr) return; auto it = std::find(_callbacks.begin(), _callbacks.end(), callback); if (it == _callbacks.end()) { _callbacks.push_back(callback); } else { throw; } } void f() {}; void g() {}; /* evt.RegisterCallback(f); // works fine evt.RegisterCallback(g); // works fine evt.RegisterCallback(f); // throws exception */ 

If you don't like this approach, you can write your own pointer class with support for the equality operator.

+2
source share

Another solution is to have a class with the std :: function member and another compiler, and then overload () to get the std :: function parameter and call it with the parameter, and the == operator to compile the class using the compilation element.

CompareableFunction.h:

 class CompareableFunction { public: CompareableFunction(int nId, std::function<void(parameter)> handler); ~CompareableFunction(); void operator()(parameter param); bool operator== (CompareableFunction compareableFunc); private: std::function<void(parameter)> m_handler; int m_nId; }; 

CompareableFunction.cpp:

 CompareableFunction::CompareableFunction(int nId, std::function<void(parameter)> handler) { m_nId = nId; m_handler = handler; } CompareableFunction::~CompareableFunction() { } void CompareableFunction::operator()(parameter param) { return m_handler(param); } bool CompareableFunction::operator==(CompareableFunction compareableFunc) { return (m_nId == compareableFunc.m_nId); } 

EDIT: you can convert a std :: function to a C-style function pointer and use it for comparison. conversion example here: http://www.cplusplus.com/forum/general/63552/

0
source share

All Articles