Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::make_shared ternary return doesn't compile

I'm using Visual Studio 2010 and have factory for creating one of two implementations of an abstract base class. The factory Create method takes a bool flag and returns one of the two impls in a shared_ptr. Using an if statement works fine for me, but the compiler complains when I try to use a ternary with make_shared calls.

class Base {
public:
   Base() {};
};

class Foo : public Base {
public:
    Foo() {};
};

class Bar : public Base {
public:
    Bar() {};
};

class Factory {
public:
    static std::shared_ptr<Base> Create(bool isFoo) {
        return isFoo ?
            std::make_shared<Foo>() :
            std::make_shared<Bar>();
    }
};

int main() {
    std::shared_ptr<Base> instance = Factory::Create(true);
    return 0;
}

The error VS is giving is 'No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called c:\path\file.h(78): error C2668: 'std::tr1::shared_ptr<_Ty>::shared_ptr' : ambiguous call to overloaded function with [ _Ty=Base ]

Note that

static std::shared_ptr<Base> Create(bool isFoo) {
    if (isFoo)
        return std::make_shared<Foo>();
    return std::make_shared<Bar>();
}

compiles just fine.

like image 293
Kevin Avatar asked Dec 19 '22 13:12

Kevin


1 Answers

It's because both the second and third expression in a ternary operation must be convertible to each other. In your case std::shared_ptr<Foo> is simply not convertible to std::shared_ptr<Bar>, and the other way around.

While they both can be converted to std::shared_ptr<Base> they are not convertible to each other.

like image 152
Some programmer dude Avatar answered Jan 01 '23 16:01

Some programmer dude