C++ 参考包装容器(需要比较运算符?)

C++ 参考包装容器(需要比较运算符?),c++,stl,boost,containers,tr1,C++,Stl,Boost,Containers,Tr1,如果将stl容器与POD类型的引用包装器一起使用,则以下代码就可以正常工作: 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; 仅声明上面的比较运算符是不够的,通常必须声明: b

如果将stl容器与POD类型的引用包装器一起使用,则以下代码就可以正常工作:

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;
仅声明上面的比较运算符是不够的,通常必须声明:

bool operator==(const boost::reference_wrapper<Integer>& lhs, const Integer& rhs)
{
 return boost::unwrap_ref(lhs)==rhs;
}
bool运算符==(常量boost::reference_包装器和lhs、常量整数和rhs)
{
返回升压::展开参考(lhs)=rhs;
}
还有可能:

bool operator==(const Integer& lhs, const boost::reference_wrapper<Integer>& rhs)
{
 return lhs==boost::unwrap_ref(rhs);
}
bool运算符==(常量整型&lhs,常量boost::reference\u包装器&rhs)
{
返回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;
整数j={0};
std::vectorjs;
js.push_back(boost::ref(j));

std::cout当您声明原始比较例程时,上面的示例是否有效:

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);
}

请注意,在类中声明友元比较例程与声明成员函数比较例程不同,这就是为什么这些例程可以工作,而原始代码可能无法工作。

更喜欢非成员函数而不是成员函数。这种情况就是其中一个原因。当它是一个成员函数时,操作员要求左侧为特定类型。相反,当它是一个自由函数时,可以对任何可转换为参数的类型调用它,而
reference\u wrapper
就是这样。@GMan:当然,这是有道理的,谢谢你的解释!的确是的,谢谢!我觉得答案会非常简单。
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);
}
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);
}