I am parsing a text based file to read variables from it. Existence of variables in the file is important, so I decided to write a template class which will hold both value of the variable (Value) and its existence flag (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;
}
};
The stored variable type will occasionally be std::vector, so I overloaded the subscript operator operator[] to directly access the elements of the vector. So that I can make the Value and Exists members private.
I use this class like this in the code:
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.
}
I get the following error message:
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)
What am I doing wrong here?
optional(which doesn't require thatTypeis default constructible).