如果是模板,则包含头文件。

发布于 2024-12-07 03:57:43 字数 205 浏览 1 评论 0原文

当我们创建一个类时,我们在头文件中声明其函数并在源文件中定义它们...然后可以将头文件包含在主文件中以使用该类...

但是如果我们在头文件中声明模板类文件并在 .cpp 文件中定义它,然后如果我们在 main(包含 int main)文件中包含头文件,那么为什么会出现链接器错误......并且如果我们包含 .cpp,则不会出现错误主文件中的文件(包含头文件)...任何答案请问?

When we make a class we declare its functions in a header files and define them in a source file... then the header file can be included in the main file to use the class...

But if we declare a template class in header files and define it in the .cpp file and then if we include the header file in the main(containing int main) file then why does a linker error crop up... and the error does not crop up if we included the .cpp file(containing the header file ) in the main file... any answers plz?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神仙妹妹 2024-12-14 03:57:43

在编译器读取源代码时,模板实际上并不生成任何目标代码;它们(通常)仅在实际使用模板时才被“实例化”。因此,如果您在一个源文件中定义模板函数,并从另一个源文件中调用它,则模板函数的代码根本不会被编译:它不在第一个目标文件中,因为没有任何东西需要它,并且它不在第二个目标文件,因为编译器无权访问函数的定义。

您在头文件中定义模板函数,以便在调用模板函数的每个翻译单元中,编译器可以访问其代码,并可以编译专门使用适当模板参数的副本。

或者,您可以使用显式实例化:您定义模板.cpp 文件中的函数, 还准确地告诉编译器应该编译该函数的类型。这更难维护,因为您必须跟踪程序的其余部分需要哪些实例化。如果有东西调用 foo(),但您仅显式实例化了 foo()foo() >,您会收到缺少符号错误。

您不应该从另一个 .cpp 文件中#include .cpp 文件。只需将模板函数定义及其声明放在标头中即可。

Templates don't actually produce any object code at the point where the compiler reads their source code; they're (typically) only "instantiated" when something actually uses the template. So if you define a template function in one source file, and call it from another, the code for the template function doesn't get compiled at all: it's not in the first object file since nothing there needed it, and it's not in the second object file since the compiler didn't have access to the function's definition.

You define template functions in header files so that in each translation unit where something calls the template function, the compiler has access to its code and can compile a copy of it specialized with the appropriate template arguments.

Alternatively, you can use explicit instantiation: you define the template function in a .cpp file, and also tell the compiler exactly which types that it should compile the function for. This is harder to maintain, because you have to keep track of which instantiations are needed by the rest of the program. If something calls foo<float>(), but you've only explicitly instantiated foo<int>() and foo<char>(), you get a missing-symbol error.

You shouldn't #include a .cpp file from another .cpp file. Just put the template function definitions in the header together with their declarations.

蓝海似她心 2024-12-14 03:57:43

模板既不是类也不是函数。它是编译器用来生成类或函数的模式。

这里有很好的解释

A template is neither a class nor a function. Its a pattern that compiler uses to generate classes or functions.

Very nicely explained in HERE

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文