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.
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.
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