0

I am trying to a create a class TemplateTest<T> which accepts a single parameter - the class T. I have the following code which declares the class TemplateTest and the constructor:

//in TemplateTest.h

#ifndef TEMPLATETEST_H
#define TEMPLATETEST_H

template<class T>

class TemplateTest
{
    T property;

   public:
       TemplateTest(T value);
};

#endif // TEMPLATETEST_H
//in TemplateTest.cpp

#include<iostream>
#include "TemplateTest.h"

using namespace std;

template<class T>

TemplateTest<T>::TemplateTest(T value)
: property(value) {};

I'm not sure where the error is, but when I call the constructor in main.cpp with a parameter p I get the message: undefined reference to TemplateTest<p>::TemplateTest(p).

//in main.cpp

#include<iostream>
#include "TemplateTest.h"

int main()
{
    int g = 6;

    TemplateTest<int> temp(g);

    return 0;
}

//returns "undefined reference to TemplateTest<int>::TemplateTest(int)

What am I doing wrong?

R. Burton
  • 111
  • 6
  • 4
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – UnholySheep Jun 10 '20 at 19:36
  • @UnholySheep Possibly... I'm still not sure why the constructor isn't working. I would assume that what I have written would fall under `doSomething` in the linked answer with `TestType` as the return type, but it should be working if that's the case. – R. Burton Jun 10 '20 at 22:48
  • No, because `doSomething` in the linked answer is defined *inside* the class declaration. You are trying to define your constructor *outside* the class declaration, inside a separate file. That would only work if your header has `#include "TemplateTest.cpp"` as the final line (and the cpp file doesn't include the header), which is what the second variant in the accepted answer does – UnholySheep Jun 10 '20 at 22:59

0 Answers0