关于cpp中的template多文件限制

记得以前看到过关于cpp中的template不能将声明与实现分开的说明,但是今天看别人代码时发现又是可以的,觉得很奇怪,自己去查了一下cpp标准的说明,

Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation
(definition) of a template class or function must be in the same file as its declaration. That means that we cannot
separate the interface in a separate header file, and that we must include both interface and implementation in any
file that uses the templates.

这是为什么呢?

其实正解应该是这样的,所谓多文件其实是以编译单位来说的,而头文件根本不算是一个编译单位,它只是作为附属被include进来而已,因此这个限制是说,如果在A.cpp里实现了一个模板方法(或者类),那么如果需要在B.cpp里调用这个方法或者类,那么就会出现链接错误,因为链接器不知道跟谁链接。但是如果你只是在同一个编译单元里使用的话,那是没有任何问题的。比如你可以在A.hpp里声明一个模板函数,而在A.cpp里实现它,但是只要你不需要在别的文件(比如B.cpp)里使用这个方法,那是没有任何问题的。可是你一旦使用了这个方法,那就会报链接错误。

你可能感兴趣的:(template)