Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

#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();
}
like image 959
LT21j Avatar asked Mar 03 '23 06:03

LT21j


1 Answers

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 :-) ).

Whereas std::unique_ptr<B> and std::unique_ptr<C> are unrelated types,

both std::unique_ptr<B> and std::unique_ptr<C> are convertible to std::unique_ptr<A>, so converting one explicitly would be enough:

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

Demo

like image 158
Jarod42 Avatar answered May 13 '23 05:05

Jarod42