这种typedef如何工作?

All*_*nzi 4 c++

我正在观看这个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;
};
Run Code Online (Sandbox Code Playgroud)

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

我创建了一个类似的类F,但是它没有编译,两个typedef之间class QScopedPointer和之间有什么区别class F

 template<typename T>
 class F{
  typedef T *F::*bool;
  public:
   operator bool(){return true;}
 };
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 6

typedef T *QScopedPointer::*RestrictedBool;
Run Code Online (Sandbox Code Playgroud)

当我们移动星星时,这可以清楚地表明:

typedef T* QScopedPointer::* RestrictedBool;
//      ^~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~
//       the type             the alias
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,我们将更清楚地写为

using RestrictedBool = T* QScopedPointer::*;
Run Code Online (Sandbox Code Playgroud)

RestrictedBool这里声明为类型别名T* QScopedPointer::*.所以typedef T *F::bool失败是因为你无法重新定义bool:)这个名字很容易让人误解,因为这个类型实际上并不是一个布尔值.

类型T* QScopedPointer::*指向成员的类型.这种类型接受类中的任何T*成员QScopedPointer<T, cleanup>,例如我们看到

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.
};
Run Code Online (Sandbox Code Playgroud)

为什么不是QScopedPointer<T>因为QScopedPointer模板?

在里面QScopedPointer<T, cleanup>,QScopedPointer可以使用类名来代替QScopedPointer<T, cleanup>.这称为本地声明的名称.有关详细信息,请参阅 不带模板参数的C++模板名称 .