Templated function being reported as “undefined reference” during compilation

前端 未结 3 725
长发绾君心
长发绾君心 2021-01-28 04:19

These are my files:

--------[ c.hpp ]--------

#ifndef _C
#define _C

#include
class C
{
public:
    template void ca         


        
相关标签:
3条回答
  • 2021-01-28 04:46

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

    0 讨论(0)
  • 2021-01-28 04:56

    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.

    0 讨论(0)
  • 2021-01-28 05:03

    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'

    0 讨论(0)
提交回复
热议问题