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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With