9

A templated member function, with template arguments not used in the parameter list can be called in the following form:

struct C { template <class> func (); };
C c;
C.func <int>();

But how do I call a template constructor, which does not use a template parameter in its argument list?

struct D { template <class>  D (); };

Certainly

D<int> d;

Cannot be the syntax, as this is the construction of a variable of type D <int>,, which is an instantiation of class template D<class>.

This is not just an academic question, I have use for templated constructors (not using the template in the constructor argument list), basically policybased factories and currently use a dummy parameter mpl::identity <mytype>() as a workaround.

3
  • Dummy parameter is pretty much the only way I've been able to make this work...
    – Joe Z
    Dec 25, 2013 at 17:39
  • So others didnt see a possibility apart from the workaround either. Sad. But, thanks for the link. It is odd that the language on one hand allows to declare and define these constructors, which on the other hand cannot be used. A possible sytax could have been: D d<int>; Alas this might possibkly get in conflict with templated variables (C++14?). Dec 25, 2013 at 19:17

1 Answer 1

4

This is not my own knowledge, but instead taken from a few other sources, mainly the already posted C++ template constructor.

I assume, that it is not possible to instanciate template-constructors without parameters, because this could create multiple default constructors. Templates are expanded at compile-time and thus create some kind of overload on the function they create. The default-constructor cannot be overloaded, so this has to fail when you use more than one template-instance.

Apart from the dummy-variable I can only think of using a templated factory method or class (if that is possible in your case)

ex: (Using an int-template instead of class-template, since I can't think of another example at the moment)

class C
{
  int i;
  C() { }
public:
  template<int I>
  static C newInstance()
  {
    C c;
    c.i = I;
    return c;
  }
};
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.