Templated function being reported as “undefined reference” during compilation

孤街浪徒 提交于 2019-12-02 07:57:46

A way to solve this problem is to

a. remove '#include "c.hpp"' from c.cpp AND

b. include 'c.cpp' at the end of 'c.hpp' (strange sounding '#include "c.pp"')

This way the template definitions are availabe to each translation unit that includes 'c.hpp' without explicitly doing so in each .cpp file. This is called the 'inclusion model'

I believe this is because when you compile c.cpp the compiler doesn't know it needs to generate code for C::call<Merc>(Merc&), and when you're compiling main.cpp it doesn't have the definition of C::call<T>(T&) from which to instantiate C::call<Merc>(Merc&).

Template definitions are essentially semantic macros, so much like the preprocessor's #define lexical macros they must be visible in the compilation units that use them.

Essentially, you cannot have related template declarations and definitions in separate files in current C++. You should fully define class C in one file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!