通过使用std :: variant是否可以避免继承?

时间:2019-07-18 12:08:48

标签: c++

我试图查看是否可以在不使用继承的情况下重写以下代码:

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

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

我尝试使用std :: variant重写它,以便可以使用std :: holds_alternative和std :: get代替使用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
}

但是我遇到了错误:当我尝试编译上面的代码时,没有从'unique_ptr'到'unique_ptr'的可行转换。

有没有办法使上述代码正常工作,或者有另一种避免使用dynamic_cast的方法?

1 个答案:

答案 0 :(得分:3)

类型X和类型A完全不相交,因此不能将A上的指针(是否为智能指针)分配给X上的指针。

也许您应该尝试这个吗?

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