简体   繁体   中英

c++ passing std::function from another class to a constructor

I am passing a method into a constructor, but when I used a method that another class, it gives me an error.

It is currently working in this form;

unsigned int pHash(const std::string& str)
{
    //method
}
int main()
{
//stuff
HashMap* hm2 = new HashMap(pHash);
//stuff
}

However, if I reference another header file's method like so;

HashMap* hm2 = new HashMap(&HashFcn::primeHash);

I get an error at runtime with the follow messages;

Error   1   error C2100: illegal indirection    c:\program files (x86)\microsoft visual studio 11.0\vc\include\xrefwrap 273 1   Project
    Error   2   error C2440: 'newline' : cannot convert from 'const std::string *' to 'const HashFcn *' c:\program files (x86)\microsoft visual studio 11.0\vc\include\xrefwrap 273 1   Project
    Error   3   error C2647: '.*' : cannot dereference a 'unsigned int (__thiscall HashFcn::* )(const std::string &)' on a 'const std::string'  c:\program files (x86)\microsoft visual studio 11.0\vc\include\xrefwrap 273 1   Project

My hashmap constructor looks like this;

HashMap::HashMap(HashFunction hashFunction)
    : hfunc(hashFunction)

where hfunc is a typdef of a method.

I have a class HashFcn which has the method primeHash

unsigned int primeHash(const std::string&);

This is my first time doing typdef / method passing -- any clues or help would be greatly appreciated!

尝试使primeHash静态:

  static unsigned int primeHash(const std::string&);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM