我正在解析一个基于文本的文件以从中读取变量。文件中变量的存在很重要,因此我决定编写一个模板类,它将保存变量的值 ( Value
) 及其存在标志 ( Exists
)。
template<class Type>
class MyVariable
{
public:
Type Value;
bool Exists;
MyVariable()
: Exists(false), Value(Type())
{
}
MyVariable(const Type & Value)
: Exists(true), Value(Value)
{
}
MyVariable(const Type && Value)
: Exists(true), Value(std::move(Value))
{
}
MyVariable(const Type & Value, bool Existance)
: Exists(Existance), Value(Value)
{
}
MyVariable(const Type && Value, bool Existance)
: Exists(Existance), Value(std::move(Value))
{
}
size_t size() const
{
return Value.size();
}
const MyVariable & operator=(const MyVariable & Another)
{
Value = Another.Value;
Exists = true;
}
const MyVariable & operator=(const MyVariable && Another)
{
Value = std::move(Another.Value);
Exists = true;
}
const Type & operator[](size_t Index) const
{
return Value[Index];
}
Type & operator[](size_t Index)
{
return Value[Index];
}
operator const Type & () const
{
Value;
}
operator Type &()
{
Value;
}
};
存储的变量类型偶尔会是std::vector
,所以我重载了下标运算符 operator[]
直接访问 vector 的元素。这样我就可以制作 Value
和 Exists
成员私有(private)。
我在代码中这样使用这个类:
const MyVariable<std::vector<int>> AVector({11, 22, 33, 44 ,55});
for (size_t i=0; i<AVector.size(); i++)
{
std::wcout << L"Vector element #" << i << L" --> " << AVector.Value[i] << std::endl; // Works okay.
std::wcout << L"Vector element #" << i << L" --> " << AVector[i] << std::endl; // Gives error.
}
我收到以下错误消息:
Error C2679 binary
'<<'
: no operator found which takes a right-hand operand of type'const std::vector<int,std::allocator<_Ty>>'
(or there is no acceptable conversion)
我在这里做错了什么?
最佳答案
const Type & operator[](size_t Index) const
{
return Value[Index];
}
Type & operator[](size_t Index)
{
return Value[Index];
}
那些返回类型是错误的;您返回的是包含的类型,而不是容器类型。您可以为此使用 decltype
:
auto operator[](size_t Index) const -> decltype(Value[Index])
{
return Value[Index];
}
auto operator[](size_t Index) -> decltype(Value[Index])
{
return Value[Index];
}
关于c++ - 重载类下标运算符以访问成员 std::vector 对象的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34016439/