views:

105

answers:

4

Hello!

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

Thank you.

+2  A: 

You can create a templated factory function:

class Foo
{
public:
    template <class T> static Foo* create() // could also return by value, or a smart pointer
    {
        return new Foo(...);
    }
...        
};
Samuel_xL
But what about normal objects.
Martin York
@Martin: I think this could also return by value (a non-pointer). RVO should take care of eliminating the copy anyway.
UncleBens
+4  A: 

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

You are wrong. It doesn't conflict in any way. You just can't call it ever.

Johannes Schaub - litb
+3  A: 

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.

James McNellis
+1  A: 

Some points:

  • If you declare any constructor(including a templated one), the compiler will refrain from declaring a default constructor.
  • Unless you delcare a copy-constructor (for class X one that takes X or X& or X const &) the compiler will generate the default copy-constructor.
  • If you provide a template constructor for class X which takes T const & or T or T& then the compiler will nevertheless generate a default non-templated copy-constructor, even though you may think that it shouldn't because when T = X the declaration matches the copy-constructor declaration.
  • In the latter case you may want to provide a non-templated copy-constructor along with the templated one. They will not conflict. When X is passed the nontemplated will be called. Otherwise the templated

HTH

Armen Tsirunyan