如果是模板,则包含头文件。
当我们创建一个类时,我们在头文件中声明其函数并在源文件中定义它们...然后可以将头文件包含在主文件中以使用该类...
但是如果我们在头文件中声明模板类文件并在 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在编译器读取源代码时,模板实际上并不生成任何目标代码;它们(通常)仅在实际使用模板时才被“实例化”。因此,如果您在一个源文件中定义模板函数,并从另一个源文件中调用它,则模板函数的代码根本不会被编译:它不在第一个目标文件中,因为没有任何东西需要它,并且它不在第二个目标文件,因为编译器无权访问函数的定义。
您在头文件中定义模板函数,以便在调用模板函数的每个翻译单元中,编译器可以访问其代码,并可以编译专门使用适当模板参数的副本。
或者,您可以使用显式实例化:您定义模板
.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 callsfoo<float>()
, but you've only explicitly instantiatedfoo<int>()
andfoo<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.模板既不是类也不是函数。它是编译器用来生成类或函数的模式。
这里有很好的解释
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