I need to write a data structure which may possibly need to contain very large objects, so dynamic memory allocation is a must. I've never needed to do dynamic allocation of objects that use templates so I am a little confused as to why this is not working. I've posted a very basic view of what I'm trying to do
Everything builds correctly, but when I try to test my constructors and create a test Container object, I get a "/home/darkestfright/Programming/C++/Container/main.cpp:15: undefined reference to `Container<double>::Container()'" error.
main.cpp:
1 2 3 4 5 6 7 8
#include <iostream>
#include "Container.h"
int main()
{
Container<double> *testContainer = new Container<double>();
return 0;
}
Your class named Container in the header, but Bag in the .cpp file.
also -- you generally can't separate template classes into cpp files like this because template classes are generated as needed by the .cpp files that use them. IE: main.cpp creates a Container<double>, but it cannot generate the code for Container<double> because it can't see the code for Container's member functions.
The general approach to this is to keep everything in the template class in the header.
Or, of course, you could just use std::vector. You're re-inventing the wheel here.
Technically: No. There are ways to work around it. One of the easiest is to put the implementation in a separate header file and #include it in the normal header. IE:
1 2 3 4 5 6 7 8 9
// in container.h
template <class T>
class Container
{
// ...
};
#include "container.hpp" // or "container_imp.h" or whatever
1 2 3
// in container.hpp / container_imp.h
// <put function bodies just as you would if this were a normal .cpp file
Another alternative is to explicitly instantiate all the forms of the template you'll need so that they'll be externally linked... but that is generally a big pain in the butt.