-2

I was experimenting bit with a c++ then I stumbled upon this problem:- binary '<<': no operator found which takes a right-hand operand of type 'c1'

What is causing such problem?

using c1 = enum class Color : unsigned int {
    red,
    green,
    blue,

};
int main()
{
    c1 col{ Color::red };
    std::cout << "Value of col is " << col;
}

when I use enum followed just the name Color it prompts an warning:-

The enum type 'Color' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

0

to print the index of the elements of the enum class one must use the static_cast or use the ones suggested in the comment box.

 std::cout << static_cast<unsigned int>(Color::red);

//it should print index 0

0

You can just cast it to unsigned int if you want to print the value. And if you want the string printed, then you have to write a function for that, like below:

#include <string> // For std::string
#include <iostream>
using c1 = enum class Color : unsigned int {
    red,
    green,
    blue,

};


inline std::string ColorToString(c1 color)
{
    switch (color)
    {
        case c1::red: return "red";
        case c1::green: return "green";
        case c1::blue: return "blue";
    }
    return "";
}


int main()
{
    c1 col{ Color::red };
    
    // If you are trying to output the name of the enum
    std::cout << "Name of col is " << ColorToString(col) << std::endl;
    
    // If you are trying to output the value of the enum
    std::cout << "Value of col is " << static_cast<unsigned int>(col) << std::endl;

}

Demo

Rid
  • 397
  • 2
  • 12