2016-03-03 109 views
1

最近,我在使用Template Metaprogramming(使用现代C++设计作为我当前的参考)构建个人库方面取得了进展。用于C++模板的声明和定义分离

我一直在想最好的方式来布局我的模板代码。显然,编译器希望模板的定义在声明的同一个文件中可见。但是,我想将声明从定义中分离出来,所以当我只想查看方法原型或其他东西时,我不太会去查看。

因此,要解决这个问题,我已经开始做可以通过下面的例子来说明:

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 

我个人喜欢这个比在一个文件中拥有所有东西,但我我很好奇,如果任何人有任何提示接近这个或任何推理,可能会让我考虑只是把它全部存入一个文件。

回答

0

一种方法我想是这样做:

Header.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 

Header.hxx:

template <typename T> 
void A<T>::go (T const& value) { } 

,这是相当多的,你做什么。我省略了另一个文件中的File Guard,并给出了一个让人们知道不要导入它的名字。

我对此有好运。它需要人秒弄明白,但.hxx帮助至少有一个位(“这是不同的; OK,如何有什么不同?”)

+0

我喜欢做的实现头文件与怀念稍有不同的延伸。它很微妙,但正如你所说,它有助于表明它与定义标题不同。直到你的例子我还没有意识到有一个.hxx扩展名!我会等待看到其他任何回应,看看是否还有其他有趣的方法。 – spektr