1

The standard ios class overrides the void * operator such that it can be used in conditionals.

if (std::cin) { ... }

I have a class whose function returns a status.

Status DoSomething()

It would be good to be able to use Status in an if-statement if the use doesn't need a fine-grained return status.

if (DoSomething()) { ... }  // just want to know if pass or fail

// or if I need more info
Status s = DoSomething()
switch (s) { ... }

Is the ios trick good for this use case or not? Is it even a good idiom in general?

2
  • 2
    What is Status? A Enum, Class or just #define int?
    – Ian Yang
    Dec 15, 2011 at 15:05
  • It could be anything that makes it the safest (and preferably the easiest) to implement what I'm trying to achieve.
    – Russell
    Dec 15, 2011 at 15:12

2 Answers 2

4

Is it even a good idiom in general?

No. In C++03 you should instead use safe-bool idiom. In C++11, you should use explicit operator bool. Never use operator void* to do bool conversion. They have to be defined on Status type, obviously.

Note that this doesn't affect switch — to be able to use that, you need to have a conversion operator to an integer or an enumeration.

2
  • Nice, thanks for the link. And I really like the name Cat Plus Plus. :)
    – Russell
    Dec 15, 2011 at 15:13
  • 1
    If a conversion to enum or integer exists, it has higher priority when converting to bool than operator void*
    – Ian Yang
    Dec 15, 2011 at 15:53
0

If you only has one error status, an enum is OK. Just assign 0 to that only error status.

Otherwise you need a class. But a class cannot be used in switch, you need a conversion operator to integer type (bool, int, chat, enum etc). Once you have such conversion operator defined, they have higher priority than "void*" when the context requires a bool value. If you define both int and bool operator, they will lead to bool conversion ambiguous. So you cannot use an object in both if and switch, except the only error status is converted to 0.

However, you can use the safe-bool idiom (do not use operator bool, which can be used in switch accidentally), and add a function to return enum, or integer for switch.

class Status {
public:
    enum Code {
        RUNNING = 1,
        IDDLE = 2,
        ERROR = -1,
        STOPPED = -2
    };

    explicit Status(Code code) : code_(code) {}

    bool ok() const { return code_ > 0; }

    operator void*() const
    { return ok() ? const_cast<Status*>(this) : 0; }

    bool operator!() const
    { return !ok(); }

    Code code() const { return code_; }

private:
    Code code_;
};

Status s(Status::STOPPED);

if (s) { .... }
switch (s.code()) { .... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.