c++模板声明和实现分离

  在学习C++泛型编程或者接触过STL源码的同学,一定对模板声明和实现放置在一起编写印象非常深刻。相交于C++非泛型编程,我们习惯上将函数的声明和实现分开存放,一来是代码更加“干净”,二来即使提供给三方使用也不会泄漏源码实现。那C++模板声明和实现能够分离吗?

一、C++模板声明和实现不分离

  下面是Node类模板声明和实现采用不分离的方式编写步骤:

  1. 创建一个node.h(node.hpp)头文件,后缀一般为:*.h或*hpp:
  2. 类(Node)模板的声明和实现:
 1 template <typename T>
 2 class Node
 3 {
 4 public:
 5     Node(const T& data)
 6         : _data(data)
 7         , _next(nullptr)
 8     {
 9     }
10     ~Node()
11     {
12         if (_next) {
13             delete _next;
14             _next = nullptr;
15         }
16     }
17     const T& GetData() const
18     {
19         return _data;
20     }
21     const Node* const GetNext() const
22     {
23         return _next;
24     }
25 private:
26     T _data;
27     Node* _next;
28 };

  或:

 1 template <typename T>
 2 class Node
 3 {
 4 public:
 5     Node(const T& data);
 6     ~Node();
 7     const T& GetData() const;
 8     const Node* const GetNext() const;
 9 private:
10     T _data;
11     Node* _next;
12 };
13 
14 
15 template <typename T>
16 Node<T>::Node(const T& data)
17     : _data(data)
18     , _next(nullptr)
19 {}
20 
21 template <typename T>
22 Node<T>::~Node()
23 {
24     if (_next) {
25         delete _next;
26         _next = nullptr;
27     }
28 }
29 
30 template <typename T>
31 const T& Node<T>::GetData() const
32 {
33     return _data;
34 }

  采用这种非分离方式,根据个人习惯或者编写规则,一二方式皆可。

二、c++模板声明和实现分离

  1. 创建一个node_separate.h(node_separate.hpp)头文件,后缀一般为:*.h或*hpp:
  2. 类(Node)模板的声明:
 1 template <typename T>
 2 class Node
 3 {
 4 public:
 5     Node(const T& data);
 6     ~Node();
 7     const T& GetData() const;
 8     const Node* const GetNext() const;
 9 private:
10     T _data;
11     Node* _next;
12 };
13 
14 #include "node_separate.inl" // 重点关注点

  3.类(Node)模板的实现(node_separate.inl)

 1 #include "node_separate.h"
 2 
 3 template <typename T>
 4 Node<T>::Node(const T& data)
 5     : _data(data)
 6     , _next(nullptr)
 7 {
 8 }
 9 
10 template <typename T>
11 Node<T>::~Node()
12 {
13     if (_next) {
14         delete _next;
15         _next = nullptr;
16     }
17 }
18 
19 template <typename T>
20 const T& Node<T>::GetData() const
21 {
22     return _data;
23 }
24 
25 template <typename T>
26 const Node<T>* const Node<T>::GetNext() const
27 {
28     return _next;
29 }

  采用分离方式,需要注意两点:

  1. 模板声明最后需要包含模板实现文件;
  2. 模板实现文件后缀名称*.inl

  其他地方无区别。当然,模板声明和实现分离早期还有其他方式实现,这里就不再赘诉。目前主流分离方式还是采用我上面介绍的方式。下面是C++并行算法库:https://github.com/NVIDIA/thrust

posted @ 2021-06-20 23:01  blackstar666  阅读(1218)  评论(0编辑  收藏  举报