Home > database >  Using a pointer to a member function as a key in unordered_map
Using a pointer to a member function as a key in unordered_map

Time:03-06

I have a unordered map std::unordered_map<void (MyClass::*)(), double> used to store the time that has elapsed since a function has been called. I'm getting an error saying that

error: use of deleted function ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = void (MyClass::*)(); _Tp = double; _Hash = std::hash<void (MyClass::*)()>; _Pred = std::equal_to<void (MyClass::*)()>; _Alloc = std::allocator<std::pair<void (MyClass::* const)(), double> >]’

What is causing this, and how do I fix it? Is there a better way to do what I trying to do?

CodePudding user response:

std::unordered_map stores its data using some calculations involving std::hash function. As described in the documentation for std::hash, under subsections "Standard specializations for basic types" and "Standard specializations for library types", there are only limited types that std::hash can perform on and void (MyClass::*)() is not one of them since its user-defined.

One possible solution is to std::bit_cast your pointer to the appropriate integer type and store the int as a key. Another solution is to use std::string as the key and when a function is called use the __func__ as the key inside the function.

  • Related