演算子+オーバーロードされたテンプレートクラスでのポリモーフィズムの使用。基本クラスを実装する方法は?

sphexoo

さまざまなサイズの行列とベクトルのテンプレートクラスを作成しようとしています。私のVectorクラスでは、+ =および+演算子をオーバーロードして、同じ長さの2つのベクトルを追加できるようにしました。長さが一致しない場合、コンパイラーにエラーをスローさせます。

これらのmvc :: Vectorオブジェクト(長さが異なる)をstd :: vector内に複数保存したいと思います。

そのために、すべてのmvc :: Vectorオブジェクトを継承する基本クラスmvc :: VectorBaseを作成しました。

今私は書くことができます

std::vector<std::unique_ptr<mvc::VectorBase>> vectorBuffer;

vectorBufferからMyVectorのメンバー関数を呼び出せるようにするために、これらのメンバーに純粋仮想関数を追加して、使用できるようにしました。

vectorBuffer[0]->GetLength().

私の問題:VectorBase演算子のオーバーロードがわからないため、のようなコードを記述できません

mvc::Vector<2> result = (*vectorBuffer[0]) + (*vectorBuffer[1]);

演算子のオーバーロードを純粋な仮想として追加しようとしてmvc::VectorBaseも機能しませんでした。これは、1つの引数がmvc::Vectorテンプレートクラスのテンプレート引数である必要があるためです。これはテンプレートの外部では使用できません

#include <vector>
#include <memory>

#define T float

namespace mvc
{
    class VectorBase
    {
    public:
        // virtual Vector operator+= (Vector<Tlength>& other) = 0;
        virtual int GetLength() const = 0;
    };

    template<int Tlength>
    class Vector : public VectorBase
    {
    private:
        T vec[Tlength];

    public:
        Vector operator+ (Vector<Tlength>& other)
        {
            for (int i = 0; i < Tlength; i++)
            {
                vec[i] += other.vec[i];
            }
            return *this;
        }

        int GetLength() const
        {
            return Tlength
        }
    }
}

int main()
{
    mvc::Vector<3> vec3_1;
    mvc::Vector<3> vec3_2;
    mvc::Vector<4> vec4_1;

    mvc::Vector<3> result = vec3_1 + vec3_2; // this line works properly 
    mvc::Vector<3> result = vec3_1 + vec4_1; //this line won´t compile (as expected)

    std::vector<std::unique_ptr<mvc::VectorBase>> vectorBuffer;

    vectorBuffer.push_back(std::make_unique<mvc::Vector<2>>());
    vectorBuffer.push_back(std::make_unique<mvc::Vector<2>>());

    mvc::Vector<2> result = (*vectorBuffer[0]) + (*vectorBuffer[1]); // <-- this is what i want to be able to do
}

目的の動作を実装するにはどうすればよいですか?

vectorBuffer[0] + vectorBuffer[1] MyVectorオブジェクトが同じテンプレートで生成された場合にのみ機能します(Tlengthが等しい)

これは、MyVectorの2つの別々に保存されたインスタンスですでに機能します。

ポリモーフィズムを使用して複数のmvc :: Vectorオブジェクトを同じstd :: vectorに格納すると、失敗します。

編集:

+演算子を戻り値の型として基本クラスでオーバーロードすることにより、要求された動作が得られました。

#include <vector>
#include <memory>
#include <iostream>

#define T float

namespace mvc
{
    class VectorBase
    {
    public:
        virtual VectorBase* operator+ (VectorBase& other) = 0;
        virtual int GetLength() const = 0;
        virtual T GetElem(int i) const = 0;
        virtual void Print() const = 0;
    };

    template<int Tlength>
    class Vector : public VectorBase
    {
    private:
        T vec[Tlength];

    public:
        Vector(T initValue)
        {
            for (int i = 0; i < Tlength; i++)
            {
                vec[i] = initValue;
            }
        }

        VectorBase* operator+ (VectorBase& other) override
        {
            if (other.GetLength() != Tlength)
            {
                std::cout << "[Error]: Argument dimensions mismatch. Program will terminate." << std::endl;
                std::cin.get();
                exit(-1);
            }

            //Vector<Tlength> tmpOther = dynamic_cast<Vector<Tlength>&>(other);

            for (int i = 0; i < Tlength; i++)
            {
                //vec[i] += tmpOther.vec[i];
                vec[i] += other.GetElem(i);
            }
            return this;
        }


        Vector<Tlength> operator+ (Vector<Tlength>& other)
        {
            for (int i = 0; i < Tlength; i++)
            {
                vec[i] += other.GetElem(i);
            }
            return *this;
        }

        int GetLength() const override
        {
            return Tlength;
        }

        T GetElem(int i) const override
        {
            return vec[i];
        }

        void Print() const override
        {
            for (int i = 0; i < Tlength; i++)
            {
                std::cout << " " << vec[i] << "\n";
            }
            std::cout << std::endl;
        }
    };
}

int main()
{
    /* without polymorphism */
    // vector1
    mvc::Vector<2> vec3_1 = mvc::Vector<2>(1.2f);
    vec3_1.Print();
    // vector2
    mvc::Vector<2> vec3_2 = mvc::Vector<2>(3.4f);
    vec3_2.Print();
    // vector2 = vector1 + vector2
    vec3_2 = vec3_1 + vec3_2;
    vec3_2.Print();

    /* with polymorphism */
    // vector buffer storing base class objects
    std::vector<mvc::VectorBase*> vectorBuffer;
    //vector1
    vectorBuffer.push_back(new mvc::Vector<3>(3.5f));
    vectorBuffer[0]->Print();
    //vector2
    vectorBuffer.push_back(new mvc::Vector<3>(2.8f));
    vectorBuffer[1]->Print();
    //vector2 = vector1 + vector2
    vectorBuffer[1] = *vectorBuffer[0] + *vectorBuffer[1];
    vectorBuffer[1]->Print();

    std::cin.get();

    for (unsigned int i = 0; i < vectorBuffer.size(); i++)
    {
        delete vectorBuffer[i];
    }
}

plus演算子は、「非多形」の使用法もサポートするために2回オーバーロードされます。(メイン内の例を参照)

operator +オーバーライドの内部には、@ VikasAwadhiyaのdynamic_castソリューションを使用した表彰があります。これも機能します。現在、仮想ゲッター関数GetElemを使用した現在のソリューションと比較したパフォーマンスについてはわかりません。

今のところ、私はそれを生のポインターでしか動作させることができませんでした。まだunique_ptrソリューションに取り組んでいます。

すべての返信をありがとう!

r3mus n0x

これを行うには、仮想operator+リターンを作成し、基本クラスを受け入れます

class VectorBase
{
public:
    virtual int GetLength() const = 0;
    // We have to return a heap allocated object because the actual type and,
    // hence, its size is unknown
    virtual std::unique_ptr<VectorBase> operator+(VectorBase& other) = 0;
};

template<int Tlength>
class Vector: public VectorBase
{
private:
    // ...

    std::unique_ptr<VectorBase> operator+(VectorBase& other) override
    {
        if (other.GetLength() != Tlength)
            return nullptr; // or throw an exception if you want

        Vector result = *this + static_cast<Vector<Tlength>&>(other);
        // or "new Vector<Tlength>(result)" if your compiler doesn't support C++14
        return std::make_unique<Vector<Tlength>>(result);
    }

    // ...
};

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ