Dependent Origination

Posts Tagged ‘template function

say I have this template function in a header file.

class A {

template<typename T>

bool my_function(T& t);

}

And its implementation is in a separate cc file. There has been undefined reference errors during linking and I was puzzled. Luckily, amid the puzzling, I noticed that my class A has other functions, which are not template, and which are compiling and linking fine. So this is no visibility issue but gotta be related to it being a template function.

This realization then makes subsequent googling easy: here is exactly same problem on StackOverflow. The solution is you have to put implementation into the same header file, because the compiler has to see the implementation at the time of compiling — it has to be able to instantiate the function during compiling stage. In other words, it has to produce a compiled version of the instantiation of the templated function. It cannot wait until link time.

Remember I have met the same problem years ago, while I was new at the previous job and spent hours figuring out this. Hopefully now I remember this and won’t be puzzled any more in the future 🙂


December 2019
M T W T F S S
« Nov    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Twitter

Flickr Photos