我有一个无序映射 std::unordered_map
用于存储自调用函数以来所经过的时间。我收到一条错误消息,指出
error: use of returned function 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = void (MyClass::*)( ); _Tp = 双; _Hash = std::hash; _Pred = std::equal_to; _Alloc = std::allocator; >]'
是什么原因造成的,如何解决?有更好的方法来做我想做的事情吗?
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?
发布评论
评论(1)
std::unordered_map
使用一些方法存储其数据涉及std::hash
函数。正如std::hash
的文档中所述,在“基本类型的标准专业化”和“库类型的标准专业化”小节中,只有有限的类型std::hash< /code> 可以执行,而
void (MyClass::*)()
不是其中之一,因为它是非静态的,并且在没有对象的情况下不能使用非静态方法指针。一种可能的解决方案是使用
std::string
作为键,并且在调用函数时使用__func__
作为函数内的键。这是一个可行的解决方案:
为什么我们需要使用
methodWrapper
?为什么我们不能将FuncPtr
作为键类型传递给m_functionMap
?因为非静态方法指针不能在没有对象的情况下使用。这就是这条看起来奇怪的线的原因:我认为静态方法解决方案更有意义:
总之,我的建议是使用
__func__
。std::unordered_map
stores its data using some calculations involvingstd::hash
function. As described in the documentation forstd::hash
, under subsections "Standard specializations for basic types" and "Standard specializations for library types", there are only limited types thatstd::hash
can perform on andvoid (MyClass::*)()
is not one of them since its non-static and a non-static method pointer can not be used without an object.One possible solution is to use
std::string
as the key and when a function is called use the__func__
as the key inside the function.This is a working solution:
Why do we need to use
methodWrapper
? Why can't we just passFuncPtr
as key type to them_functionMap
? Because non-static method pointers can not be used without an object. That's the reason for this strange-looking line:and the static method solution which I belive makes more sense:
In conclusion my suggestion is using
__func__
.