c++templatesconstructorfunction-templates

Is it possible to have a constructor template with no parameters?


I wish to have a non-template class with a template constructor with no arguments.

As far as I understand, it's impossible to have it (because it would conflict with the default constructor - am I right?), and the workaround is the following:

class A{
   template <typename U> A(U* dummy) {
       // Do something
   }
};

Maybe there is a better alternative for this (or a better workaround)?


Solution

  • There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:

    Foo<int> f = Foo<int>();
    

    The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the constructor template's argument list to go.

    Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.