samedi 23 mai 2020

Find a unique_ptr to an inherited class object emplaced_back in a vector

I am trying to implement an Entity Component System (ECS) for my game. I have a base class "Component" (referred here as A) which is inherited by child class like HealthComponent(referred here as B), DamageComponent (referred here C)

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

class A
{
public:
    A() : VarA(10){}

    int VarA;
    const std::string ClassName = "A";
    virtual void prnt(){ std::cout << "A class" << std::endl; }
};

class B : public A
{
public:
    B() : VarB(20){}
    int VarB;
    const std::string ClassName = "B";
    void prnt(){ std::cout << "B class" << std::endl; }

    bool operator== (const B& other) const
    {
        return this->ClassName == other.ClassName;
    }

};

class C : public A
{
public:
    C() : VarC(30){}
    int VarC;
    const std::string ClassName = "C";
    void prnt(){ std::cout << "C class" << std::endl; }

    bool operator== (const B& other) const
    {
        return this->ClassName == other.ClassName;
    }
};

int main()
{
    std::vector<std::unique_ptr<A>> ObjVector;
    std::vector<std::unique_ptr<A>>::iterator ObjIterator;

    A* object1 = new B();
    std::unique_ptr<A> bptr{object1};
    ObjVector.emplace_back(std::move(bptr));

    A* object2 = new C();
    std::unique_ptr<A> cptr{object2};
    ObjVector.emplace_back(std::move(cptr));

    ObjIterator = std::find(ObjVector.begin(), ObjVector.end(), B);

    return 0;
}

on compiling the code

-------------- Build: Debug in STL (compiler: GNU GCC Compiler)---------------

x86_64-w64-mingw32-g++.exe -Wall -g -std=c++11  -c C:\Users\admin\Desktop\code\C++\STL\main.cpp -o obj\Debug\main.o
x86_64-w64-mingw32-g++.exe  -o bin\Debug\STL.exe obj\Debug\main.o   
C:\Users\admin\Desktop\code\C++\STL\main.cpp: In function 'int main()':
C:\Users\admin\Desktop\code\C++\STL\main.cpp:58:66: error: expected primary-expression before ')' token
   58 |     ObjIterator = std::find(ObjVector.begin(), ObjVector.end(), B);
      |                                                                  ^

I tried using "new B()" and "(&B)" as the last parameter in std::find function but it still gave me the same error. Please Help.

Aucun commentaire:

Enregistrer un commentaire