簡體   English   中英

這種轉換為bool的方式如何工作?

[英]How does this conversion to bool work?

我正在學習Cinder框架。 這個框架中有一個Texture類,可以這樣使用:

Texture myImage;
myImage.loadImage(/*...*/);
if(myImage)
{
    // draw the image.
}

我對此感到困惑,因為myImage是一個對象。 用它作為條件對我來說毫無意義。 我期望像myImage.exist();這樣的東西myImage.exist(); 因此,我逐步完成了代碼,結果發現Texture類定義了一個轉換運算符:

public:
    //@{
    //! Emulates shared_ptr-like behavior
    typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type;
    // What is this???
    operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; }
    void reset() { mObj.reset(); }
    //@}  

Obj定義為:

protected:      
    struct Obj {
        Obj() : mWidth( -1 ), mHeight( -1 ), mCleanWidth( -1 ), mCleanHeight( -1 ), mInternalFormat( -1 ), mTextureID( 0 ), mFlipped( false ), mDeallocatorFunc( 0 ) {}
        Obj( int aWidth, int aHeight ) : mInternalFormat( -1 ), mWidth( aWidth ), mHeight( aHeight ), mCleanWidth( aWidth ), mCleanHeight( aHeight ), mFlipped( false ), mTextureID( 0 ), mDeallocatorFunc( 0 )  {}
        ~Obj();

        mutable GLint   mWidth, mHeight, mCleanWidth, mCleanHeight;
        float           mMaxU, mMaxV;
        mutable GLint   mInternalFormat;
        GLenum          mTarget;
        GLuint          mTextureID;
        bool            mDoNotDispose;
        bool            mFlipped;   
        void            (*mDeallocatorFunc)(void *refcon);
        void            *mDeallocatorRefcon;            
    };
    std::shared_ptr<Obj>        mObj;

我知道operator int() const可以將Object隱式更改為int,但是unspecified_bool_type如何工作? 調試器在operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; }處停止operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; } operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; } operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; }if(myImage)執行時。

我可能對這里的語法有些困惑,這是什么

typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type;

意思?

並且做

void (*mDeallocatorFunc)(void *refcon); 

在Obj中,意味着mDeallocatorFunc是Class Obj的成員,它是具有原型的函數的函數指針: void xxx(void *)

這是安全的布爾習語 它不僅僅使用operator bool()因為隱式轉換會對該運算符造成各種麻煩。 因此,它使用隱式可轉換為bool的類型(例如指向成員的指針),並且這種類型的危險性最小。

幸運的是,在C ++ 11中不需要這種破解,因為我們可以改為編寫explicit operator bool而不會成為隱式轉換的犧牲品。

暫無
暫無

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

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