【发布时间】:2015-07-12 12:58:11
【问题描述】:
我是 Stack Overflow 和 C++ 的新手!那么问题来了:
目标是使用下一个接口创建容器类:
IContainer.h:
class ElemNotFound {};
template < class ElemType, class IndexType > class IContainer
{
public:
virtual const ElemType& GetElem(const IndexType& index) const throw (ElemNotFound) = 0;
virtual void PutElem(const IndexType& index, const ElemType& elem) throw () = 0;
};
当前使用该接口的代码是:
#include "IContainer.h"
#include <vector>
class Container : public IContainer < class ElemType, class IndexType >
{
private:
struct ContainerElement
{
IndexType& Index;
ElemType& Data;
};
std::vector < ContainerElement > MyVector;
std::vector < ContainerElement > ::iterator MyIterator;
public:
// EDIT: that operator== part is incorrect as
// failed attempt to circumvent inability to compare custom types
friend bool operator== (IndexType& x, const IndexType& y)
{
if (x == y) return 1;
else return 0;
}
const ElemType& GetElem(const IndexType& index)
{
try
{
MyIterator = MyVector.begin();
while (MyIterator != MyVector.end())
{
if (MyIterator->Index == index)
// PROBLEM: missing operator "==" for IndexType == const IndexType
{
// do useful things
}
MyIterator++;
}
}
catch (Exception e) // everything down below is a placeholder
{
throw (ElemNotFound) = 0;
}
}
void PutElem(const IndexType& index, const ElemType& elem)
{
}
};
IndexType 和 const IndexType 的直接比较(使用“==”)不起作用,原因我不知道。我想比较我的向量中的自定义索引和我在函数中使用的索引以从容器中获取元素。对自定义类型使用运算符重载“==”也不起作用。应该是不正确的继承还是不正确地使用运算符重载 - 我不知道!
那么问题来了:如何比较使用模板的类中的 const 和非 const 自定义类型变量?
【问题讨论】:
-
您的
operator==函数是否有理由不通过常量引用获取both 参数?无论如何,运算符函数中的比较不会递归调用自身吗? -
Joachim,那部分代码只是为了规避无法直接编写
(MyIterator->Index == index)的尝试。我知道这是不正确的 - 错误仍然存在。为什么我不能比较自定义类型和 const 自定义类型 - 我不知道。在 C++ 标准描述和 C++ 文献中也找不到答案。 -
ElemType和IndexType定义在哪里? -
@SergeiBorodin 非 const 类型隐式转换为 const 类型。只需比较两个 const 类型
-
不应该 operator== 比较两个
const Container&而不是 IndexTypes?
标签: c++ templates comparison constants operator-keyword