我正在解析基于文本的文件以从中读取变量。文件中变量的存在很重要,因此我决定编写一个模板类,该类将同时容纳变量的值(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 的元素。这样我就可以将ValueExists成员设为私有(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.
}

我收到以下错误消息:



我在这里做错了什么?

最佳答案

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/

10-11 22:46
查看更多