簡體   English   中英

最好不要對模板化類分開函數聲明和定義嗎?

[英]Is it a good practice to not to separate function declarations and definitions for templated classes?

通常,在非模板化類中,我們將函數聲明和定義分為單獨的文件(.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  ***/

某些函數(例如“ Koenig運算符”)不能在類本身之外定義:

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

這是一個非模板朋友unique_ptr<T>對於每個模板實例生成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上觸摸文件系統或相同的緩存),但是與其他因素相比,通常不會很大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM