0

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 ?:

1 Answer 1

2

C++ cannot infer that you want the expression to be a std::unique_ptr<Base>, so you can cast one of them and C++ can then infer the cast for the other:

base = condition ?
    (std::unique_ptr<Base>) std::make_unique<SubClassA>():
    std::make_unique<SubClassB>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.