mercredi 7 décembre 2022

How can I return an arbitrary superclass of an abstract generic class and call its generic methods?

I've got an abstract class that uses variable template.

template <class T>
class Abstract
{
public:
    virtual void print(T t) = 0;
};

There can be any derivatives of the class like so:

class A : public Abstract<std::string>
{
public:
    void print(std::string str)
    {
        std::cout << str << std::endl;
    }
};

class B : public Abstract<int>
{
public:
    void print(int number)
    {
        std::cout << std::to_string(number) << std::endl;
    }
};

Now I want a function to return one of these derivatives so I can execute the print method. And here is my Problem:

template (class T); // error here
Abstract<T> &f(int n) // what should the return type look like?
{
    if (n == 0)
    {
        A a{};
        return a;
    }
    else
    {
        B b{};
        return b;
    }
}

int main()
{
    A a{f(0)};
    a.print("foo");

    B b{f(1)};
    b.print(42);

    return 0;
}

So how is it be possible to return a class with unknown parameter type and call its methods?

I already tried returning a superclass without templates which works fine. As soon as templates are added code wont compile. I also tried void* and reinterpret_cast. Problem here is that I have manually to decide to what type to cast to.

So how can I return an arbitrary superclass of an abstract generic class and call its generic methods?

Aucun commentaire:

Enregistrer un commentaire