0

Here are the contents of the files. First the templated class : in the .h file :

template <class T>
class templatedClass
{
    public :

    templatedClass(T val);
    ~templatedClass() {}

    void writeV();

    T v;
};

in the .cpp file :

template <class T>
templatedClass<T>::templatedClass(T val)
{
    v = val;
}

template <class T>
void templatedClass<T>::writeV()
{
    std::cout << v << std::endl;
}

Everything is fine when build.

Now the inherited class : in the .h file :

class inheritedClass : public templatedClass<float>
{
    public :

    inheritedClass(float val);
    ~inheritedClass() {}

    void write();
};

in the .cpp file :

inheritedClass::inheritedClass(float val)
: templatedClass<float>(val)
{

}

void inheritedClass::write()
{
    writeV();
}

When building I received the following link errors :

Undefined symbols for architecture x86_64:
  "templatedClass<float>::writeV()", referenced from:
      inheritedClass::write() in inheritedClass.o
  "templatedClass<float>::templatedClass(float)", referenced from:
      inheritedClass::inheritedClass(float) in inheritedClass.o

What is wrong with my code? Have I to use special building options in XCode to succeed?

Thank you for your answer.

JLDB
  • 31
  • 3

1 Answers1

0

You have a missing template class instantiation problem. To solve it, you should put your template implementation code in the header file. By which I mean, this part:

template <class T>
templatedClass<T>::templatedClass(T val)
{
    v = val;
}

template <class T>
void templatedClass<T>::writeV()
{
    std::cout << v << std::endl;
}

There are other options, such as keeping a separate template implementation file and including it in the other cpp file, or instantiating the class template somewhere else altogether...

See Why can templates only be implemented in the header file? or class template instantiation for more details.

Community
  • 1
  • 1
Martin J.
  • 5,028
  • 4
  • 24
  • 41