【问题标题】:Is it a good practice to not to separate function declarations and definitions for templated classes?不将模板类的函数声明和定义分开是一种好习惯吗?
【发布时间】:2019-01-15 14:01:33
【问题描述】:

通常在非模板类中,我们将函数声明和定义分开到单独的文件中(.h 和 .cpp)

[1] 但上述做法似乎不适用于模板类。是否建议在单独的文件中编写实现,然后将其包含在 .h 文件的底部?

[2] 以下哪种方案通常建议用于模板类?
[a] 一次性声明和定义或
[b]同一文件中的单独声明和定义

考虑到我们必须注意的复杂语法,如果我们选择 [b]

例如。 [一]

template <typename T>
class unique_ptr final {
  private:
    T* ptr_;
  public:
    unique_ptr (T* ptr = nullptr) noexcept {
      : ptr_{ ptr } {
    }

    friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
      return lhs.get() == rhs.get();
    }
};

[b]

template <typename T>
class unique_ptr final {
  private:
    T* ptr_;
  public:
    unique_ptr (T* ptr = nullptr) noexcept;      
    friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs);

/*** implementations inside the class after all declarations (I am not sure if this makes the code code any easier to understand)  ***/
  };

/**** Implementations outside the class ***/
/***  Convoluted things needed to make friend functions work ***/
/** like mentioned in : https://stackoverflow.com/questions/3989678/c-template-friend-operator-overloading  ***/

【问题讨论】:

  • 这是个人喜好和团队编码准则的问题。

标签: c++ c++11 templates compiler-errors


【解决方案1】:

某些函数,例如“Koenig 运算符”,不能在类本身之外定义:

friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
  return lhs.get() == rhs.get();
}

这是unique_ptr&lt;T&gt; 的非模板朋友,为unique_ptr 的每个模板实例化生成。 C++ 中没有允许在unique_ptr 之外定义其主体的语法。 (您可以创建外部定义的模板友元,但不能创建参数依赖于模板类的模板参数的非模板友元)。

我们可以通过以下方式解决这个问题:

friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
  return equal(lhs, rhs);
}

然后将equal定义为unique_ptr的模板朋友。

但即使在那里,你也可以这样做:

template <typename T>
class unique_ptr final {
  private:
    T* ptr_;
  public:
    unique_ptr (T* ptr = nullptr) noexcept {
      : ptr_{ ptr } {
    }

    friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs)
#include "unique_ptr_t_operator_equal_function_body.inc"
};

如果你真的想拆分实现和接口。

将实现和接口分离到单独的.h.inc 文件、将定义内联在模板声明中或将定义放在.h 文件的末尾没有技术障碍。使用多个文件对编译时间的影响很小(因为文件系统或相同的缓存通常必须在 #include 上触及),但与其他因素相比,这通常并不大。

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2017-07-15
    • 2013-10-13
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2021-07-12
    相关资源
    最近更新 更多