lundi 28 octobre 2019

How to make a unique pointers to polymorphic classes using the ternary operator?

I'm trying to set a variable using the ternary operator. However, the compiler is complaining about incompatible types. I'm sure there is a way to do this. I have tried static casting to the base class, but I haven't been able to get the correct syntax.

#include <iostream>
#include <memory>
struct A
{
    virtual void test() {std::cout << "A" << std::endl;} 
};

struct B: public A
{
    void test() final {std::cout << "B" << std::endl;} 
};

struct C: public A
{
    void test() final {std::cout << "C" << std::endl;} 
};

int main()
{
    bool t = true;
    // Try to cast try a base unique class ptr. Maybe use static_cast??
    std::unique_ptr<A> aptr = t ? std::make_unique<B>(): std::make_unique<C>();
    aptr->test();
}

Aucun commentaire:

Enregistrer un commentaire