且构网

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

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

更新时间:2023-02-12 14:42:39

您必须在调用网站上提供模板定义。这意味着没有 .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.