vargss
vargss

Reputation: 39

operators for enum inside class

I have a class which has enum members. These members require output operator. I know how to implement operator if enum is outside the class:

enum Type
{
    SMALL=1,
    MIDDLE=2,
    LARGE=3
};

std::ostream& operator<<(std::ostream& out, const Type value){
    static std::map<Type, std::string> strings;
    if (strings.size() == 0){
        #define INSERT_ELEMENT(p) strings[p] = #p
        INSERT_ELEMENT(SMALL);     
        INSERT_ELEMENT(MIDDLE);     
        INSERT_ELEMENT(LARGE);             
        #undef INSERT_ELEMENT
    } 
    return out << strings[value];
}

class House
{
public:
    Type houseType;
    ...
};

int main(int argc, char** argv){
    House myhouse;
    std::cout << "This house is " << myhouse << std::endl;
    return 0;   
}

Is it possible to do it with enum inside the class? I tried in similar way, but it obviously fails because operator inside class does not allow second argument.

Upvotes: 2

Views: 481

Answers (2)

eerorika
eerorika

Reputation: 238311

Is it possible to do it with enum inside the class?

Yes, and it works in exactly the same way. You simply need to use the scope resolution operator since in that case the enum is no longer in global scope:

std::ostream& operator<<(std::ostream& out, const House::Type value)

Upvotes: 5

Cory Kramer
Cory Kramer

Reputation: 117856

You can again define operator<<, but basically make it a passthrough from House to Type

std::ostream& operator<<(std::ostream& out, const House& value)
{
    out << value.houseType;
    return out;
}

Working demo

Upvotes: 2

Related Questions