且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模板问题导致链接器错误 (C++)

更新时间:2023-02-12 14:07:36

您必须在调用站点上提供您的模板定义.这意味着没有 .cpp 文件.

You have to have your template definitions available at the calling site. That means no .cpp files.

原因是模板无法编译.把函数想象成饼干,而编译器就是一个烤箱.

The reason is templates cannot be compiled. Think of functions as cookies, and the compiler is an oven.

模板只是一个曲奇饼,因为它们不知道它们是什么类型的曲奇饼.它只告诉编译器在给定类型时如何制作函数,但它本身无法使用,因为没有具体的类型被操作.你不能做饼干刀.只有当你准备好美味的饼干面团时(即,给编译器面团 [类型]))你才能切割饼干并烹饪它.

Templates are only a cookie cutter, because they don't know what type of cookie they are. It only tells the compiler how to make the function when given a type, but in itself, it can't be used because there is no concrete type being operated on. You can't cook a cookie cutter. Only when you have the tasty cookie dough ready (i.e., given the compiler the dough [type])) can you cut the cookie and cook it.

同样,只有当你实际使用某个类型的模板时,编译器才能生成实际的函数,并编译它.但是,如果缺少模板定义,则无法执行此操作.你必须把它移动到头文件中,这样函数的调用者才能制作cookie.

Likewise, only when you actually use the template with a certain type can the compiler generate the actual function, and compile it. It can't do this, however, if the template definition is missing. You have to move it into the header file, so the caller of the function can make the cookie.