簡體   English   中英

這種typedef如何工作?

[英]How does this typedef work?

我正在觀看這個cpp閃電談話視頻 ,它在0:37顯示了這段代碼

template<typename T, typename cleanup = QScopedPointerDeleter<T>>
class QScopedPointer{

typedef T *QScopedPointer::*RestrictedBool; // how does this work? 
                           //why not QScopedPointer<T> since QScopedPointer is a template?

public:
inline operator RestrictedBool() const 
 {
  return isNull()? Q_NULLPTR : &QScopedPointer::d;
 }

 inline bool isNull() const{ return !d;}

protected:
 T *d;
};

我很難理解typedef T *QScopedPointer::*RestrictedBool; , 這是什么意思?

我創建了一個類似的類F ,但它沒有編譯, class QScopedPointerclass F的兩個typedef有什么區別?

 template<typename T>
 class F{
  typedef T *F::*bool;
  public:
   operator bool(){return true;}
 };
typedef T *QScopedPointer::*RestrictedBool;

當我們移動星星時,這可以清楚地表明:

typedef T* QScopedPointer::* RestrictedBool;
//      ^~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~
//       the type             the alias

在C ++ 11中,我們將更清楚地寫為

using RestrictedBool = T* QScopedPointer::*;

這里的RestrictedBool被聲明為T* QScopedPointer::*的類型別名。 所以typedef T *F::bool失敗,因為你無法重新定義bool :)這個名字很容易讓人誤解,因為這個類型實際上並不是一個布爾值。

類型T* QScopedPointer::*指向成員的類型。 此類型在此接受QScopedPointer<T, cleanup>類中的任何T*成員,因此我們可以看到

class QScopedPointer {
    operator RestrictedBool() const {
//           ^~~~~~~~~~~~~~
//            this function returns a `RestrictedBool` = `T* QScopedPointer::*`
        return isNull()? Q_NULLPTR : &QScopedPointer::d;
//                                   ^~~~~~~~~~~~~~~~~~
//                                    and this expression has type `T* QScopedPointer::*`
    }

    T *d;
//  ^~~
//   the `d` member has type `T*` in the `QScopedPointer` class.
};

為什么不QScopedPointer<T>因為QScopedPointer是一個模板?

QScopedPointer<T, cleanup> ,可以使用類名QScopedPointer代替QScopedPointer<T, cleanup> 這稱為本地聲明的名稱 有關詳細信息,請參閱不帶模板參數的C ++模板名稱

暫無
暫無

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

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