我正在解析基于文本的文件以从中读取变量。文件中变量的存在很重要,所以我决定编写一个模板类,它将保存变量的值(Value
)及其存在标志(Exists
)。重载类下标运算符以访问成员的元素std :: vector对象
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[]
直接访问向量的元素。这样我就可以使Value
和Exists
成员保密。
我在代码中使用这个类是这样的:
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.
}
我收到以下错误信息:这需要的右手操作没有操作员发现:
错误C2679二进制
'<<'
类型'const std::vector<int,std::allocator<_Ty>>'
(或没有可接受的转换)
我在做什么错在这里?
你可以看看'optional'(不要求'Type'是缺省构造)。 – Jarod42