So I was getting a linking error in my c++ project and a stackoverflow post mentioned that template methods need to also be defined in the header instead of the source file.
The code for that specific method is (after combinging the declaration / definition):
struct Timer {
template <typename T>
const long getDuration() const;
};
template <typename T>
const long Timer::getDuration() const {
long time = static_cast<long>(std::chrono::duration_cast<T>(end - start).count());
return time > 0 ? time : 1L;
}
Now the explaination was that for templates, the compiler needed the definition in order to be able to process it but that does not seem to be the case all the time.
For example, this is code that to me looks similar as the code above however I can place the declaration in the header file and the definition in source file:
// Enity.hpp
class Entity {
public:
template <typename T>
bool hasComponent() const;
}
// Entity.cpp
template <typename T>
bool Entity::hasComponent() const {
return componentBitSet[getComponentTypeId<T>()];
}
I am still relatively new to modern c++ so I am trying to understand why in the first example I need the declaration and definition in the same file and in the second, they can be split out.