user11802791
user11802791

Reputation:

Is it possible to avoid inheritance by using std::variant?

I was trying to see if I can rewrite the following code without using inheritance:

struct X {};
struct A : X {};
struct B : X {};

int main() {
    std::unique_ptr<X> xptr = std::make_unique<A>();
}

I tried rewriting it using std::variant so that I can make use of std::holds_alternative and std::get instead of using dynamic_cast:

struct A;
struct B;
using X = std::variant<A, B>;
struct A {};
struct B {};

int main() {
    X x = A();                                        // works
    std::unique_ptr<X> xptr = std::make_unique<A>();  // doesn't work
}

But I'm getting the error: no viable conversion from 'unique_ptr' to 'unique_ptr' when I try to compile the code above.

Is there a way to make the above code work, or is there another way to avoid using dynamic_cast?

Upvotes: 3

Views: 210

Answers (1)

prog-fh
prog-fh

Reputation: 16920

Type X and type A are totally disjoint, so pointer (smart or not) on A cannot be assigned to pointer on X.

May be should you try this?

std::unique_ptr<X> xptr = std::make_unique<X>(A{});

Upvotes: 3

Related Questions