c++ - C++ 模板的声明和定义分离

标签 c++ templates header-files template-meta-programming

最近我在使用模板元编程构建个人库方面取得了进展(使用现代 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/

相关文章:

ios - 使用 CocoaPods 将头文件复制到包含文件夹

c++ - 将 map 与自定义对象一起使用时出错?可能是语法问题

c++ - C++ 中的默认函数参数必须保持不变吗?

c++ - Luabridge:删除时堆损坏(_CrtIsValidHeapPointer)

c++ - 隐藏第三方C++头文件的内容

c - 多次包含头文件

c++ - 推导原始类型的知识,同时转发

C++ 构造函数中不需要的隐式转换

c++ - 模板函数特化默认

c++ - 在模板类 C++ 中使用函数指针