I've been writing some C++ code recently. I've encountered a situation in which a template class would be perfect for me, but I'm not sure about defining its members in .cpp
file. I want to precise that I know about certain problems happening to template classes divided into header and source files, but I have no idea how can I implement any template classes in real projects, while keeping my code organized.
Consider a vector class:
vector.h
template <typename T>class Vector { ... public: Vector(); ...};
vector.cpp
#include "vector.h"template <typename T>Vector<T>::Vector() { //body}
Of course, defining an object in main.cpp
:
#include "vector.h"int main() { Vector<int> v();}
causes the compilator to produce an error:
main.cpp:(.text+0x1c): undefined reference to `Vector<int>::Vector()
How do people deal with such errors?
I've read that explicit declaration of class type, e.g. Vector<int>
solves the issue, but I feel like I don't understand something and that it's kinda the opposite of this whole template idea.