Can someone explain this C++ wizardy:
#include <memory>
class Base
{
public:
Base(){}
};
class SubClassA : public Base
{
public:
SubClassA(){}
};
class SubClassB : public Base
{
public:
SubClassB(){}
};
int main()
{
std::unique_ptr<Base> base;
bool condition = true;
if(condition) {
base = std::make_unique<SubClassA>(); //This works
}
else {
base = std::make_unique<SubClassB>(); //This works
}
base = (condition) ?
std::make_unique<SubClassA>(): //Does not work
std::make_unique<SubClassB>();
return 0;
}
This code produces the error:
main.cpp: In function ‘int main()’:
main.cpp:41:24: error: operands to ?: have different types ‘std::_MakeUniq::__single_object {aka std::unique_ptr >}’ and ‘std::_MakeUniq::__single_object {aka std::unique_ptr >}’
base = (condition) ?
~~~~~~~~~~~~^
std::make_unique<SubClassA>():
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::make_unique<SubClassB>();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How can I do the assignment with the ternary operator ?: