运算符重载和迭代器混淆

Operator overloading and iterator confusion

本文关键字:迭代器 重载 运算符      更新时间:2023-10-16

我使用此代码来查找长方体(g)在d方向上最远的点typedef vector_t point_t;

std::vector<point_t> corners = g.getAllCorners();
coordinate_type last_val = 0;
std::vector<point_t>::const_iterator it = corners.begin();
point_t last_max = *it;
do
{
    coordinate_type new_val = dot_product( *it, d );
    if( new_val > last_val )
    {
        last_val = new_val;
        last_max = *it;
    }
}
while( it != corners.end() );
return last_max;

对于命名空间point中的类vector_t,我还有一个用于运算符!=的模板运算符重载。

namespace point
{
    template 
    <
        typename lhs_vector3d_impl, 
        typename rhs_vector3d_impl
    >
    bool operator!=( const typename lhs_vector3d_impl& lhs, const typename rhs_vector3d_impl& rhs )
    {
        return binary_operator_not_equal<lhs_vector3d_impl, rhs_vector3d_impl>::apply( lhs, rhs );
    }
};

重载在大多数情况下都很好,但当我与迭代器(即it != corners.end())一起使用时,它会崩溃,因为我不打算在这种情况下使用此函数。我可以说这是因为模板参数解析出错,但我不知道为什么:

lhs_vector3d_impl=std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<legend::geometry::point::Carray_Vector3d<int32_t>>>>,
rhs_vector3d_impl=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<legend::geometry::point::Carray_Vector3d<int32_t>>>>

我知道调用了错误的函数,但我不明白为什么…

因此,基本上我的问题是,如何使用我的函数而不是std命名空间中的运算符来解决comme迭代器comparaison,以及如何防止使用此函数。

注1:我是从模板开始的,所以我可能在不知情的情况下做错了什么,如果是这样,请告诉我。

注2:这个代码主要用于学术目的,所以我真的想手工完成大部分。

注意3:使用Visual Studio 2012 C++编译器

我不明白你为什么需要这个模板函数。但很明显,当您只想将lhs和rhs类型用于point_t 时,它可能已经推断出它们是iterator

两种解决方案:

  1. 删除运算符定义上的模板,并使用pointt作为类型(所以您可以肯定)
  2. 删除using命名空间以确保他看到namespace point之外的迭代器

如果您真的需要重载运算符!=尽管它是通用的,也就是说,只需要任何两个参数,即几乎匹配你传递给它的任何东西,你可以通过显式调用标准库版本:来避免它被迭代器首选

std::operator !=(it, corners.end())