Download

Inconsistent behavior with templates

I’m using templated version of functions as getters to help with casting. I’m using Visual studio community 2019

While the declaration for those getters were in the header files for my classes ,the definition for those templates were actually in class’s cpp file. From what I read it is a bad practice and should break the code immediately, but it didn’t.

I used those template version of function at a few places in my game code by only including the header and there were no issues for sometime. The code compiled with no errors and ran as expected . Even the parts using the templated functions ran as expected.

As I continued adding more code that used the templated getters all of a sudden it broken out of nowhere and there were a bunch of missing symbols errors for those templated functions that were working a moment ago.

I rolled back the changes on git and everything was still working on older revisions.

I added few lines of new code step by step and it broke again , but this time it complained about a different templated getter function that was running fine earlier.

Even something as refactoring the name of a non-templated function would suddenly trigger the compiler to generate template function errors.

Finally I moved all template function definitions from cpp to header files and and everything started working again.

While I intend to keep it that way , my question is more out of curiosity:

Why were those template functions working fine for sometime even with their definitions in CPP files ?

And why were different template functions breaking depending on from where I extended my code?

This may answer your question:
https://isocpp.org/wiki/faq/template…s-defn-vs-decl

The TL;DR is that templated functions must be defined where they are declared.