5

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

DanielGr
  • 191
  • 1
  • 6
  • 2
    How do you call it with raw new ?... You cannot. same for `make_...` – Jarod42 Dec 30 '15 at 02:49
  • AFAIK a constructor cannot be templated unless it has an input parameter that uses the template: `template A(T t) { ... }`. You cannot specify the template value when calling the constructor (`new A()` is not allowed) but the compiler can infer the type based on the input parameter, eg: `new A(value);`. So it goes with the `make_...()` functions. There is no way to specify a constructor template parameter type, but if the constructor accepts input parameters then `make...()` can pass its own input parameters to the constructor and let the compiler infer the template type(s). ` – Remy Lebeau Dec 30 '15 at 02:57

1 Answers1

6

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982