i seem to have some problem in creating a structure defined as the topic.
My objective is to create a sort of event handler, (it doesn't matter if it's good or bad programming,or if it is not multithread: for the moment is just for practice).
My idea is then to create a vector of pointers to functions, and place this vector in a map,where the key is a string.
i must be doing something conceptually wrong, because i get some strange errors: My code is as following (errors are at the end):
.h file
//ptr to function
typedef int (*pt2Function)(void*);
typedef std::vector<pt2Function> fPtrVector;
class eventDispatcher
{
public:
//stuff
void addListener(std::string,pt2Function);
protected:
//stuff
std::map<std::string,fPtrVector> _listeners;
};
and here is the cpp:
.cpp file
void eventDispatcher::addListener(std::string eventName ,pt2Function function)
{
std::map<std::string,fPtrVector>::iterator it;
it=this->_listeners.find(eventName);
if(it != this->_listeners.end())
{
//do something
}
else
{
std::vector<pt2Function> tmp;
tmp.insert(function); // here occurs error 1
this->_listeners.insert(eventName,tmp); // here occurs error 2
std::cout<<"cnt: "<< this->_listeners.count();
}
}
The errors i get are:
1) no matching function for call to 'std::vector <int (*)(void*), std::allocator<int (*)(void*)> >::insert(int (*&)(void*))'
2) no matching function for call to 'std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<int (*)(void*), std::allocator<int (*)(void*)> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<int (*)(void*), std::allocator<int (*)(void*)> > > > >::insert(std::string&, std::vector<int (*)(void*), std::allocator<int (*)(void*)> >&)'
No variation of std::vector::insert()
takes a single argument: all take an iterator indicating the position to which the new element(s) must be inserted before. Use std::vector::push_back()
to add function
instead.
std::map::insert()
has several variations, but the one you are attempting to use takes the value_type
of the map
, which is defined as:
value_type std::pair<const Key, T>
in your case the value_type
is a std::pair<std::string, fPtrVector>
:
this->_listeners.insert(std::pair(eventName,tmp));
1) The insert()
method of std::vector
works by specifying a position using an iterator. For your case, you can use push_back()
.
2) Use insert(std::make_pair(eventName, tmp))
and that will create the required value type by the map.
You are looking for std::vector::push_back
( see the documentation for std::vector
here ).
You are looking for std::map::operator []
( see the documentation for std::map
here ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.