简体   繁体   English

如何使用三元运算符创建指向多态类的唯一指针?

[英]How to make 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.我已经尝试将 static 转换为基础 class,但我无法获得正确的语法。

#include <iostream>
#include <memory>
struct A
{
    virtual ~A() = default;
    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();
}

Return value of ternary expression is the common type of both expressions (in fact std::common_type might use ternary operator as part of its implementation:-) ).三元表达式的返回值是两个表达式的共同类型(实际上std::common_type可能使用三元运算符作为其实现的一部分:-) )。

Whereas std::unique_ptr<B> and std::unique_ptr<C> are unrelated types,std::unique_ptr<B>std::unique_ptr<C>是不相关的类型,

both std::unique_ptr<B> and std::unique_ptr<C> are convertible to std::unique_ptr<A> , so converting one explicitly would be enough: std::unique_ptr<B>std::unique_ptr<C>都可以转换为std::unique_ptr<A> ,因此显式转换一个就足够了:

auto aptr = t ? std::unique_ptr<A>{std::make_unique<B>()}
              : std::make_unique<C>();

Demo演示

Try this:尝试这个:

std::unique_ptr<A> aptr = t ? std::unique_ptr<A>(new B()): std::unique_ptr<A>(new C());

You can do a direct call to the constructor:您可以直接调用构造函数:

std::unique_ptr<A> aptr(t ? std::make_unique<B>(): std::make_unique<C>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM