我正在尝试实现无锁映射,但遇到了问题。
在我的迭代器类中,我实现了一个 operator->
免费获得first
和 second
:
_t_iterator_return<_Kty, _Ty> operator->()
{
_t_iterator_return<_Kty, _Ty> tmp((int&)Cur->getKey(), Cur->getValue());
return tmp;
}
这是:
template <class _Kty, class _Ty>
struct _t_iterator_return
{
_Kty& first; // key
_Ty& second; // val
_t_iterator_return(_Kty& k, _Ty& v) : first(k), second(v) {}
};
看起来很正常,不是吗?但在我的main()
这个:
for(LFMap<int, stringc>::iterator it = m.begin(); !it.end(); ++it)
fprintf(mres, "K: %7d V: %s\n", it->first, it->second.c_str());
导致编译时错误:error C2819: type 'lightforce::core::LFMap<_Kty,_Ty>::_t_iterator_return<_Kty,_Ty>' does not have an overloaded member 'operator ->'
尽管如此,这段代码:
for(LFMap<int, stringc>::iterator it = m.begin(); !it.end(); ++it)
fprintf(mres, "K: %7d V: %s\n", it.operator->().first, it.operator->().second.c_str());
已经编译成功,运行良好!为什么 ->
不工作,但是 operator->
是吗?
最佳答案
C++11 §13.5.6 [over.ref] 第 1 段指出:
... An expression
x->m
is interpreted as(x.operator->())->m
for a class objectx
of typeT
ifT::operator->()
exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
由于您从 operator->
返回的类型- _t_iterator_return<_Kty, _Ty>
- 没有 operator ->
它不能被取消引用。
添加 operator ->
至 _t_iterator_return
简单地返回 this
:
_t_iterator_return* operator->()
{
return this;
}
关于c++ - 类没有合适的运算符->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433791/