views:

218

answers:

2

Hello all,

Let's say we have a class, MyParent:

class MyParent
{
public:
  template<namespace T>
  MyParent()
  {
    T* Something;
  }
};

And a derived class, which uses this constructor:

class MyDerived : public MyParent
{
public:
  MyDerived()
  : MyParent<int>()
  {
  }
};

Then I get a compiling error, because there's ambiguity. The compiler thinks that the int is a template argument to the class, not the constructor.

How do I specify that I want the int to be an argument to the constructor?

+3  A: 

It is not possible. From the standard section 14.8.1 Explicit template argument, it notes:

[Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. ]

As noted in the comments, you would need to have the constructor take a parameter of type T (or const T &), and then have MyDerived call MyParent::MyParent with a paremeter of type int.

Greg Rogers
+4  A: 

Note that your question is not particular to inheritance. Given your code example, you cannot instantiate MyParent at all, either because it doesn't accept a template argument list or because it has no default constructor.

In order to instantiate MyParent with a constructor template, you need to provide some way for the compiler to know the template argument, and you can't do that with a no-argument constructor. You need to give MyParent's constructor a parameter. Here's an example based on code from Alf P. Steinbach:

template <typename T>
struct UseMethodsOf {};

class MyParent
{
public:
  template <typename T>
  MyParent(UseMethodsOf<T>)
  {
    T* Something;
  }
};

class MyDerived: public MyParent
{
public:
  MyDerived()
  : MyParent(UseMethodsOf<int>())
  {
  }
};
Rob Kennedy
Now you too make it as complete as it can be. One gives me the true answer, the other gives me the workaround. Thanks to you both!
Geeho