如果您将 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 类型?)。也许已经有一个优雅的解决方案,我只是还没有找到它。