运算符重载和迭代器混淆
Operator overloading and iterator confusion
我使用此代码来查找长方体(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
两种解决方案:
- 删除运算符定义上的模板,并使用pointt作为类型(所以您可以肯定)
- 删除using命名空间以确保他看到
namespace point
之外的迭代器
如果您真的需要重载运算符!=尽管它是通用的,也就是说,只需要任何两个参数,即几乎匹配你传递给它的任何东西,你可以通过显式调用标准库版本:来避免它被迭代器首选
std::operator !=(it, corners.end())
相关文章:
- 迭代器类的重载前缀增量运算符会引发分段错误
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
- 迭代器和无符号整数的重载 + 运算符
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 如何实现容器的重载和模板函数的迭代器?
- 为什么标准容器迭代器不会重载"->*"?
- 前向迭代器的重载
- VC++11映射和多映射迭代器(重载)C2535
- 重载输出运算符<<以使用 STL 列表迭代器
- 迭代器 CPP,运算符重载
- 使用常量迭代器的运算符重载
- 向量迭代器在赋值重载中不兼容
- 迭代器 - vector::itrator 和 array::iterator 的重载函数
- 如何将重载增量运算符用于迭代器
- 运算符重载和迭代器混淆
- C++ 解释重载成员函数迭代器(int i = 0) 的构造"one liner":i(i) { };
- 重载迭代器类的增量运算符
- 模板和运算符重载以及迭代器
- 模板泛型树类的模板迭代器的c++操作符重载
- 重载操作符<对于非随机迭代器