简体   繁体   中英

Operator overloading and iterator confusion

I use this code to find the point of a box ( g ) furthest in the direction 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;

I also have a template operator overload for the operator != for the class vector_t which is in the namespace point .

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

The overload works fine in most cases but when I use with iterators (ie it != corners.end() ) it breaks down since I did not intend this function in that case. I can tell it's because of the template parameters resolution going wrong but i don't know why:

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>>>>

I understand the wrong functions get called but I don't understand why…

So basically my question is how comme iterator comparaison gets resolved with my function instead of an operator in the std namespace and how can I prevent this function from being used.

Note 1: I am beginning with template so I may be doing something very wrong without knowing, if so please kindly tell.

Note 2: this code is used mainly for academic purposes so I really want to do most of it by hand.

Note 3: using Visual Studio 2012 C++ compiler

I don't see why yu need this template function. But clearly it may have deduced that lhs and rhs type are iterator when you only wanted to use it for point_t

Two solutions :

  1. remove the templates on the operator definition and use point_t as type (so you are sure)
  2. remove a using namespace to be sure that he sees the iterator outside of the namespace point

如果确实需要重载的运算符!=照原样通用,即采用任何两个参数,即几乎匹配传递给它的任何内容,则可以通过显式调用标准库版本来避免被迭代器首选:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM