0

Is it possible to use a template on a constructor, for example:

class Class {
    public:
        template<typename T>
        Class(T arg);
};

And the cpp file:

#include "class.h"

template<typename T>
Class::Class (T arg) {
    // do something
}

The constructor is called with:

int a = 0;
Class c {a};

When compiling this code, I get the following error:

/usr/bin/ld: /tmp/ccNzp4z7.o: in function `main':
main.cpp:(.text+0x1c): undefined reference to `Class::Class<int>(int)'
collect2: error: ld returned 1 exit status

The use for this would be a constructor like:

Class(std::unordered_set<T> choices, std::unordered_map<Direction, std::function<std::string(T)>> mapping);

Where each object in choices would be iterated over for each Direction in the map and passed to the corresponding function, in order to generate the object. In this case, the type used has no bearing on the class after the constructor finished executing, so I don't think that it makes sense to use a template on the entire class.

PiGuy2
  • 3
  • 3

1 Answers1

0

I suspect you've defined your ctor in the .cpp file. You must define your template in the header.

// class.hpp

class Class
{
public:
     template<typename T>
     Class( T arg )
     {
         // Define the ctor body here.
     }
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
WBuck
  • 5,162
  • 2
  • 25
  • 36
  • What does the explicit qualifier do in this case? – PiGuy2 Apr 19 '20 at 00:35
  • It stops the `ctor` from implicitly converting types. It's good practice but not necessary. You can remove it if you'd prefer. – WBuck Apr 19 '20 at 00:37
  • Can you give an example of when this would be problematic? Also, when would you use explicit in general? I've never really used it. – PiGuy2 Apr 19 '20 at 00:38
  • I'm going to direct you to another thread for that question. There are good examples explaining what issue `explicit` fixes. https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean – WBuck Apr 19 '20 at 00:40
  • Did defining the `constructor` body in the `header` fix your issue? – WBuck Apr 19 '20 at 00:41