2012-01-21 3 views
3

C++에서 "정상"단항 논리 연산자는 우리 모두가 부정 논리 연산자 !이 있음을 알고, 그것은 다음과 같이 사용할 수 있나요 이 :내 말은

if (f) 
    // Do Something 

나는 그것이 중요하지 않을 수도 있지만, 궁금해!

+0

을 얻으면 원하는 것을 얻을 수 있습니다. – maress

+0

@maress : 네, 우리는 그것을 다루었습니다. –

+0

http://www.artima.com/cppsource/safebool.html의 가능한 복제물 –

답변

7

당신은 선언하고 careful라면, bool에 암시 적 변환에 대한 operator bool()을 정의 할 수 있습니다.

또는 쓰기 :

if (!!f) 
    // Do something 
자체 operator bool() 꽤 위험 때문에
+0

나는 이렇게 할 수 있다는 것을 알고 있지만 직접 운영자는없는가요? –

+1

@ Mr.TAMER :'operator bool()'이 _direct_가 아닌가? –

+0

와우! O –

2
operator bool() { //implementation }; 
3

은, 우리가 일반적으로 뭔가를 고용라는 safe-bool idiom : C++ 11에서

class X{ 
    typedef void (X::*safe_bool)() const; 
    void safe_bool_true() const{} 
    bool internal_test() const; 
public: 
    operator safe_bool() const{ 
    if(internal_test()) 
     return &X::safe_bool_true; 
    return 0; 
    } 
}; 

, 우리는 명시 적 변환을 얻을 연산자; 따라서 연산자 bool()을 정의하여 the above idiom is obsolete :

class X{ 
    bool internal_test() const; 
public: 
    explicit operator bool() const{ 
    return internal_test(); 
    } 
};