2012-01-10 15 views
2

私はCinderフレームワークを学んでいます。 あり、この枠組みの中でクラスTextureがあり、それは次のように使用することができます:boolへのこの変換はどのように機能しますか?

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

myImageが対象ですので、私は、このことについて混乱しました。それを条件として使うことは私には意味がありません。私はmyImage.exist();のようなものを期待していました。だから私は、コードを通じて段階、およびそれがTextureクラスが定義された変換演算子を持っていることが判明:Objには次のように定義されて

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(); } 
    //@} 

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がimplictly int型にオブジェクトを変更することができることを知っていますしかし、unspecified_bool_typeはどのように機能していますか? if(myImage)が実行されている場合、デバッガはoperator unspecified_bool_type() const { return (mObj.get() == 0) ? 0 : &Texture::mObj; }で停止します。

そして、私はここで文法について少し混同されることが、

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

が何を意味するのでしょうか?

そして

OBJの中
void (*mDeallocatorFunc)(void *refcon); 

はmDeallocatorFuncは、クラスのObj、プロトタイプを持つ関数への関数ポインタのメンバーであることを意味している:void xxx(void *)

+1

"安全なブールイディオム"の呪文のようです... –

+0

@KerrekSB私はそれを持っていると思います。それは 'Texture'を' shared_ptr 'に変換できる変換演算子を定義し、残りのチェックが提供されます'shared_ptr 'によって。しかし、 'typedef std :: shared_ptrは何ですか? Texture :: * unspecified_bool_type;' mean ?? 'typedef std :: shared_ptr unspecified_bool_type;'との違いはありますか?私は文法のこの種、特に ':: *'とここで混乱しています。どうもありがとうございました。 – shengy

+0

そのことは特に(普通のポインタではない!)メンバーへのポインタですが、それ以上のコードは読めません。 SBIを実装する多くの一般的な方法がありますので、少し検索するとコードによく似た説明が見つかるかもしれません。 –

答えて

4

the safe bool idiomです。暗黙的な変換がその演算子であらゆる種類の問題を引き起こす可能性があるため、単にoperator bool()を使用しません。その代わりに暗黙的にbool(メンバーへのポインタのような)に変換可能な型を使用します。これは可能な限り危険ではありません。

幸いなことに、この種のハックはC++ 11では必要ありません。代わりにexplicit operator boolと書くことができ、暗黙的な変換に陥る可能性がないからです。

+1

関連:[C++ 11ではセーフ・ブール・イディオムが廃止されましたか?](http://stackoverflow.com/q/6242768/500104) – Xeo

関連する問題