asimes
asimes

Reputation: 5894

What does this operator method do?

I am working with some classes that were generated by someone else. Below is a section of the class, I have removed most of it because it is not relevant for this question

struct OrderStatus {
    enum Value {
        New             = (char)48,
        PartiallyFilled = (char)49,
        Filled          = (char)50,
        Cancelled       = (char)52,
        Replaced        = (char)53,
        Rejected        = (char)56,
        Expired         = (char)67,
        Undefined       = (char)85,
        NULL_VALUE      = (char)0
    };

private:
    Value m_val;

public:
    explicit OrderStatus(int    v) : m_val(Value(v))   {}
    explicit OrderStatus(size_t v) : m_val(Value(v))   {}
    OrderStatus()                  : m_val(NULL_VALUE) {}
    constexpr OrderStatus(Value v) : m_val(v) {}

    operator Value() const { return m_val; }
};

Two questions:

Upvotes: 0

Views: 82

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

As pointed out in the comments, the Value() operator is an implicit conversion operator; because of this member, you can just use an instance of the OrderStatus class in order to use its (otherwise inaccessible) m_val member. You would use this as a variable of the enum type OrderStatus::Value.

Here is a short example of using it in a switch:

#include <iostream>
//
// Insert the code from your question here!
//
int main()
{
    OrderStatus q(48);
    switch (q) {
        case OrderStatus::New:
            std::cout << "New";
            break;
        default:
            std::cout << "Something else!";
    }
    std::cout << std::endl;
    return 0;
}

Upvotes: 2

Related Questions