循环包含模板
下面的代码可以完美编译:
// MyFile.h
#ifndef MYFILE_H_INCLUDED
#define MYFILE_H_INCLUDED
template <typename Datatype>
class MyClass
{
public:
void MyMethod();
}
#include "MyFile.cpp"
#endif
// MyFile.cpp
#ifndef MYFILE_CPP_INCLUDED
#define MYFILE_CPP_INCLUDED
#include "MyFile.h"
template <typename Datatype>
void MyClass<Datatype>::MyMethod()
{
// ...
}
#endif
其他方法和函数的定义可以以相同的方式与声明分开。使用这种方法有什么缺点吗?这种行为可以依赖吗?
The following code compiles perfectly:
// MyFile.h
#ifndef MYFILE_H_INCLUDED
#define MYFILE_H_INCLUDED
template <typename Datatype>
class MyClass
{
public:
void MyMethod();
}
#include "MyFile.cpp"
#endif
// MyFile.cpp
#ifndef MYFILE_CPP_INCLUDED
#define MYFILE_CPP_INCLUDED
#include "MyFile.h"
template <typename Datatype>
void MyClass<Datatype>::MyMethod()
{
// ...
}
#endif
The definitions of other methods and functions can be separated from the declarations in the same manner. Are there any downsides to using this approach? Can this behavior be relied upon?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:因为该文件是 *.tpp 文件(不是*.cpp) 它不应包含在其他构建系统操作中。如果您已手动添加它,请将其删除。
确保包含.tpp 的唯一位置是.h 中的最后一行
Note: Because the file is a *.tpp file (not *.cpp) it should not be included by other build system operations. If you have added it manually remove it.
Make sure the only place that includes <X>.tpp is the last line in <X>.h
如果您包含
MyFile.tpp
(我将其从 .cpp 重命名),则不需要包含MyFile.h
。#include
文件就像将其内容完全复制到包含它的文件中一样。除此之外,对标题进行一些组织是一种常见的做法。 (尽管您不需要MyFile.tpp
中的包含保护,因为它应该只直接从另一个标头包含(就像 GMan 所说的那样)。)If you include the
MyFile.tpp
(I renamed it from .cpp), then you don't need to include theMyFile.h
.#include
ing a file is like exactly copying it's content into the file where it's included. Other from that, it's a common practice to organize the headers a bit. (Though you don't need the include-guards in theMyFile.tpp
, because it should only ever be included from another header directly (like GMan says).)