Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uncallable template constructor? [duplicate]

Tags:

c++

templates

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.

like image 504
koraxkorakos Avatar asked Dec 25 '13 17:12

koraxkorakos


1 Answers

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;
  }
};
like image 175
user1781290 Avatar answered Nov 09 '22 04:11

user1781290