如果您将 STL 容器与 POD 类型的 reference_wrappers 一起使用,则如下代码可以正常工作:
int i = 0;
std::vector< boost::reference_wrapper<int> > is;
is.push_back(boost::ref(i));
std::cout << (std::find(is.begin(),is.end(),i)!=is.end()) << std::endl;
但是,如果您使用非 POD 类型(人为的示例):
struct Integer
{
int value;
bool operator==(const Integer& rhs) const
{
return value==rhs.value;
}
bool operator!=(const Integer& rhs) const
{
return !(*this == rhs);
}
};
仅声明上面的比较运算符是不够的,您还必须声明:
bool operator==(const boost::reference_wrapper<Integer>& lhs, const Integer& rhs)
{
return boost::unwrap_ref(lhs)==rhs;
}
可能还有:
bool operator==(const Integer& lhs, const boost::reference_wrapper<Integer>& rhs)
{
return lhs==boost::unwrap_ref(rhs);
}
为了让等效的代码工作:
Integer j = { 0 };
std::vector< boost::reference_wrapper<Integer> > js;
js.push_back(boost::ref(j));
std::cout << (std::find(js.begin(),js.end(),j)!=js.end()) << std::endl;
现在,我想知道这是否真的是它想要完成的方式,因为它有点不切实际。似乎应该有一个更简单的解决方案,例如模板:
template<class T>
bool operator==(const boost::reference_wrapper<T>& lhs, const T& rhs)
{
return boost::unwrap_ref(lhs)==rhs;
}
template<class T>
bool operator==(const T& lhs, const boost::reference_wrapper<T>& rhs)
{
return lhs==boost::unwrap_ref(rhs);
}
reference_wrapper 的行为方式可能有一个很好的理由(可能是为了适应没有比较运算符的非 POD 类型?)。也许已经有一个优雅的解决方案,只是我还没有找到。
最佳答案
当您这样声明原始比较例程时,上面的示例是否有效:
friend bool operator==(const Integer& lhs, const Integer& rhs)
{
return lhs.value == rhs.value;
}
friend bool operator!=(const Integer& lhs, const Integer& rhs)
{
return !(lhs == rhs);
}
请注意,在类中声明友元比较例程与声明成员函数比较例程不同,这就是为什么它们可能有效而您的原始代码可能无效的原因。
关于c++ - reference_wrappers 的容器(需要比较运算符?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611556/