Search code examples
c++typeid

C++ TypeId to a constructor


I am trying to create a function that checks if type of object equal the type of argument, and if it does, create new object. My class hierarchy:

class Copier: public Action class CopierX: public Copier

So my function is:

void Copier::checkequality(Action b) {
    if (typeid(*this) == typeid(b))
    {
        Action b = new T x; //here at 'T' i want new type type(this)
    }
}

Just i think it is needed to mention - this is mentioned to be a virtual function with some 'default value', so there's another question, will it work like that:

so in this CopierX, typeid(this) will return CopierX type right?, then, i want to create something that will work like Action b = new CopierX x;

I would like to say sorry if i wrote it badly, i am fairly new to C++, i used to work a lot on simple C


Solution

  • One way to solve this would be adding Action* copy() method to the Action class and implementing it within every descendant.

    The other is using static polymorphism like this

    template<typename T>
    class Action {
    public:
    template<typename U>
    void checkequality(Action<U>** b)
    {
        if(std::is_same<T, U>::value) {
            *b = new T();
        }
    }
    };
    
    class Copier : public Action<Copier>
    {}