2

テキストベースのファイルを解析して、そこから変数を読み取ります。ファイル内の変数の存在は重要なので、変数の値 ( 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[]にできるようにします。ValueExists

このクラスをコードで次のように使用します。

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>>'(または、受け入れ可能な変換がありません)

ここで何が間違っていますか?

4

4 に答える 4

4
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];
}
于 2015-12-01T09:15:48.483 に答える