0

Possible Duplicate:
C++ invoke explicit template constructor

First imagine I have a class Data with a templated member function :-

class Data
{
public:
    template <class Loader> void load(const std::string& filename);
};

I can use this like this -

Data data;
data.load<SomeLoader>(filename);

and all works fine. I can select at compiler time via the template parameter which class I want my Data object to use to load some data.

However I can't work out how to do this with constructors...

class Data
{
public:
    template <class Loader> Data(const std::string& filename);
};

That seems to compile perfectly well, but I can't seem to work out how to actually call the function.

Data<SomeLoader> data;

That doesn't work because that would invoke a class template, not a templated constructor.

Is there some syntax I'm missing here? ( If I add a constructor paramater of SomeLoader type, then the compiler correctly infers the class to use, but that's not what I need to do here)

Community
  • 1
  • 1
jcoder
  • 29,554
  • 19
  • 87
  • 130

2 Answers2

2

You are not missing any syntax. It is impossible to explicitly use a specialisation of a constructor template.

The standard has a note about this at [temp.arg.explicit]/7:

Because the explicit template argument list follows the function template name, and because con- version 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.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
  • Can you provide some documentation on this? – Luchian Grigore Mar 14 '12 at 12:02
  • 1
    @Luchian Hardly. There won’t be a paragraph in the standard saying “there is no syntax for calling a constructor with explicit template instantiation” (by the way, you *can* do this, using placement new. But let’s not go there …) **EDIT** Oh. Apparently the standard *does* provide explicit wording on this one. How thoughtful. See duplicate. – Konrad Rudolph Mar 14 '12 at 12:12
  • @KonradRudolph: Ahh, there it is, I knew I'd seen that somewhere. – Mankarse Mar 14 '12 at 12:16
  • Hmm, well thank you. But that's irritating! – jcoder Mar 14 '12 at 12:26
  • @JohnB: You can always pass a tag parameter to the constructor, and then use argument deduction on that. – Mankarse Mar 14 '12 at 12:27
0

That is not possible to do, since the compiler is not able to deduce the type, and you can not pass it to the constructor.

Few possible solutions :
1. make the Data class a template
2. pass some parameter to the constructor. This might be a better solution to use a dependency injection and pass the loader to the constructor.

BЈовић
  • 62,405
  • 41
  • 173
  • 273