开发者

C++ using && with your class without bool/&& overload?

I was told that you can in fact do MyClass a, b; ... if (a && b) {...} without 1) overloading the && operator 2) overloading the bool operator (ex: class MyClass { ... operator bool(){return boolval; } };)

The solution was to use a pointer-to-member-function. I did not understand how to use this solution. My notes say the below but i couldn't get more then that. Does anyone know how to do this?

the function takes a private nested struct as a parameter. The reason is that that typ开发者_Python百科e can’t legally be converted into anything else – it can never be used in any expression other than a Boolean context


Note: Typically answers to [homework] questions do not immediately give away the solution. However, according to your question you already know the solution but don't understand it. I'll attempt to explain.

From the information you provided in your question, your instructor was probably talking about some variant of the safe bool idiom:

class MyClass
{
private:
    typedef void (MyClass::*SafeBoolType)() const;
    void ThisTypeDoesNotSupportComparisons() const {}
public:
    operator SafeBoolType() const {
        // The actual conditional expression would go where "true" is.
        //      ____
        //     |    |
        return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0;
    }
};

int main()
{
    MyClass a;
    MyClass b;

    if(a && b) {}      // Compiles.
    /* if(a < b) {} */ // Doesn't compile.
}

Here, we provide a type cast operator to a pointer-to-member-function, which can only be used in boolean contexts. This allows the if statement with the logical operator (&&) to compile even without a bool typecast or an && operator overload. It also prevents the if statement with the comparison operator (<) from compiling.

However, I don't understand the part in your notes that mentions "the function takes a private nested struct as a parameter". The safe bool idiom doesn't require that the member function take an unnamed struct. I suggest that you ask your instructor; it is possible that I have completely misunderstood the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜