Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call make_shared or make_unique with a templated Constructor

How can I call make_shared or make_unique on a class that has a templated constructor? Here's an example:

class A
{
    /// constructor shared ptr
    A(shared_ptr<X> x) ...

    /// constructor that creates new shared ptr
    template <class T> A() : A(make_shared<T>(...)) {}
};

make_shared<A<T>>() doesn't make sense (nor does it compile), since that would rather be for a templated class, not a templated constructor.

Neither make_shared<A><T>() nor make_shared<A>(<T>()) compile---nor look like they should. Ditto on make_shared<A, T>()

Is there any way to specify the template for the constructor call in the call to make_shared? I assume the answer would apply for make_unique; if it doesn't, please indicate that. Thanks!

(To clarify how the templating is working, I've edited the code.)

like image 489
DanielGr Avatar asked Dec 30 '15 02:12

DanielGr


1 Answers

There is no way to use a class constructor template at all without template argument deduction. So any template parameters must be deduced from arguments provided, never specified explicitly at call time.

This isn't restricted to any of the make_* functions; this is no way of initializing the object at all. That constructor cannot be called. Your compiler isn't required to complain about this constructor, but there's simply no way to call it.

like image 184
Nicol Bolas Avatar answered Nov 09 '22 03:11

Nicol Bolas