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>();
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>());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.