最近我在使用模板元编程构建个人库方面取得了进展(使用现代 C++ 设计 一书作为我当前的引用)。
我一直在思考布局模板代码的最佳方式。显然,编译器希望模板的定义在声明它的同一个文件中可见。但是,我想将声明与定义分开,这样当我只想查看方法原型(prototype)或其他内容时,我就不必再查看了。
所以为了解决这个问题,我已经开始做的事情可以用下面的例子来说明:
SomeClass.hpp
#ifndef _someclass_hpp
#define _someclass_hpp
template<typename T>
class SomeClass {
public:
...
private:
...
};
#include "SomeClass_Implementation.hpp"
#endif
SomeClass_Implementation.hpp
#ifndef _someclass_impl_hpp
#define _someclass_impl_hpp
#include "SomeClass.hpp"
/* SomeClass Implementation... */
#endif
我个人更喜欢这样,而不是将所有内容都放在一个文件中,但我很好奇是否有人有任何关于处理此问题的提示或任何可能让我考虑将其全部转储到一个文件中的推理。
最佳答案
我喜欢的一种方法是这样做:
标题.hpp:
#ifndef FileGuard_whatever // technically reserved by STL because
#define FileGuard_whatever // it starts with a capital letter
template <typename T>
class A
{
void go ( T const& value ) ;
} ;
#include "Header.hxx" // implementation details
#endif // FileGuard
标题.hxx:
template <typename T>
void A<T>::go ( T const& value ) { }
这几乎就是您所做的。我在另一个文件中省略了 File Guard 的添加,并给出了一个名称,让人们知道不要导入它。
我在这方面运气不错。人们需要一秒钟的时间才能弄明白,但是 .hxx
至少对此有所帮助(“它不一样;好的,它有什么不同?”)
关于c++ - C++ 模板的声明和定义分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35762733/