Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?


1 Answers

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{});
like image 134
prog-fh Avatar answered Jul 27 '26 02:07

prog-fh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!