3

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?

5
  • 2
    These two snippets do two completely different things. It looks like an XY problem - can you explain your original problem? Commented Jul 18, 2019 at 12:11
  • 1
    You might be interested in the following 2 posts: akrzemi1.wordpress.com/2013/11/18/type-erasure-part-i akrzemi1.wordpress.com/2013/12/06/type-erasure-part-ii Commented Jul 18, 2019 at 12:20
  • Why would you expect to be able to store a std::unique_ptr<A> in a std::unique_ptr<std::variant<A,B> >???? Commented Jul 18, 2019 at 12:29
  • You can rewrite the code to do absolutely anything, but without your requirements & constraints we couldn't possibly guarantee giving you a useful suggestion. What is it that you want to do? Commented Jul 18, 2019 at 12:35
  • The question is, why avoid inheritance if you actually need it? Commented Jul 18, 2019 at 12:38

1 Answer 1

3

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{});
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, depending on the class, using std::in_place_type_t<A> might be more efficient, as it'll avoid making a redundant copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.