10

How can I change the code below to allow creation of a Base object with a templated constructor?

struct Base {
template <typename T>
Base(int a) {}
};

 int main(int argc, char const *argv[])
{
    Base *b = new Base<char>(2);
    delete b;
    return 0;
}
duli
  • 1,621
  • 3
  • 16
  • 25

2 Answers2

-3

This thread seems to answer your question:

C++ template constructor

The bottom line is that it doesn't seem to be supported; and it's unclear what it would achieve.

Community
  • 1
  • 1
Topological Sort
  • 2,733
  • 2
  • 27
  • 54
  • Sometimes constructors handle many types but the data is only used temporarily, so having the class itself be templated is reduntant. There's not a huge need for it I guess but it makes sense. – iPherian Nov 03 '16 at 22:42
-4

The question is a bit vague. Is your intent to replace the "int a" in the Base ctor with "T a"? If so, you might want to use function template type inference, like this:

template<typename T>
Base<T> CreateBase(T a)
{
  return new Base<T>(a);
}

// Call site avoids template clutter
auto base = CreateBase(2);
Scott Jones
  • 2,880
  • 13
  • 19