C++ template function compiles in header but not implementation

前端 未结 6 1676
梦谈多话
梦谈多话 2020-12-02 14:53

I\'m trying to learn templates and I\'ve run into this confounding error. I\'m declaring some functions in a header file and I want to make a separate implementation file w

6条回答
  •  眼角桃花
    2020-12-02 15:15

    This is exactly how templates work in C++, you must put the implementation in the header.

    When you declare/define a template function, the compiler can't magically know which specific types you may wish to use the template with, so it can't generate code to put into a .o file like it could with a normal function. Instead, it relies on generating a specific instantiation for a type when it sees the use of that instantiation.

    So when the implementation is in the .C file, the compiler basically says "hey, there are no users of this template, don't generate any code". When the template is in the header, the compiler is able to see the use in main and actually generate the appropriate template code.

提交回复
热议问题