在模板的情况下包含头文件。 [英] Inclusion of header files in case of templates.

查看:196
本文介绍了在模板的情况下包含头文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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...

但是如果我们在头文件中声明一个模板类并在.cpp文件中定义它,然后如果我们将头文件包含在main(包含int main)文件中,那么为什么会出现链接器错误裁剪向上...,如果我们在主文件中包含.cpp文件(包含头文件),错误不会出现...任何答案plz?

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?

推荐答案

模板在编译器读取其源代码的时候实际上不产生任何目标代码;它们(通常)只有在实际使用模板时才实例化。因此,如果你在一个源文件中定义一个模板函数,并从另一个源文件调用它,模板函数的代码根本不会被编译:它不在第一个目标文件,因为没有什么需要它,它不在

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.

或者,可以使用显式实例化:您可以在 .cpp 中定义模板函数, code>文件,也告诉编译器它应该编译函数的哪些类型。这很难维护,因为你必须跟踪程序的其余部分需要哪些实例化。如果某事调用 foo< float>(),但是你只显式实例化了 foo< int>() foo< char>(),会出现缺少符号的错误。

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.

另一个 .cpp 文件中的$ c> #include a .cpp 只需将模板函数定义与其声明一起放在标题中。

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

这篇关于在模板的情况下包含头文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆