关于cpp中的template多文件限制
2011-01-04 11:44
183 查看
记得以前看到过关于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)里使用这个方法,那是没有任何问题的。可是你一旦使用了这个方法,那就会报链接错误。
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)里使用这个方法,那是没有任何问题的。可是你一旦使用了这个方法,那就会报链接错误。
相关文章推荐
- 关于IIS限制上传文件大小的解决办法
- 关于打开最大文件数的限制
- 关于struts2使用xml拦截器(interceptor)限制文件上传(fileUpload)大小和类型的问题,道友看一看
- 关于文件上传大小限制的总结
- 关于创建表空间的数据文件的限制
- 关于outlook 2003 PST文件大小限制管理
- 关于去掉linux打开文件数限制的办法
- 关于一次 ORA-01118: 无法添加任何其他数据库文件: 超出限制 4120 的错误处理
- 关于双击cpp文件无法直接打开,VS2008提示“向程序发送命令时出现问题”的解决
- 关于git,100MB大文件上传限制的问题,这里MARK一下
- 关于用gcc编译cpp文件的错误
- C++中template的.h文件和.cpp文件的问题
- Windows关于文件句柄数的限制
- 关于cpp文件中extern(.h)的使用
- 关于浏览器文件上传的限制
- 关于asp中的ADODB.Stream的BinaryRead读取文件大小的限制
- 关于JspSmartUpload上传文件大小限制的问题
- 关于B/S系统中文件上传的大小限制怎么做
- 关于PHP上传页面的文件大小限制的注意
- 关于php上传文件的限制