Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A4-5-1 with overloading operator<<
#1
Hi

A4-5-1 states:

Quote:Expressions with type enum or enum class shall not be used as operands to built-in and overloaded operators other than the subscript operator [ ], the assignment operator =, the equality operators == and ! =, the unary & operator, and the relational operators <, <=, >, >=.
My understanding of the rule is that confusion should be avoided when using the underlying type arithmetically.
My use-case is overloading operator<< for convenient logging and printing of an unscoped enum:


Code:
inline std::ostream& operator<<(std::ostream& os, MyEnum const& enum_value)
{
    switch (enum_value)
    {
        case MyEnum_Unknown:
        {
            return os << "Unknown";
        }
        case MyEnum_Val1:
        {
            return os << "Descriptive message... (MyEnum_Val1)";
        }//...
     }
}

Usage, where the warning is shown:
Code:
LOG_WARNING << "Could not perform action with " << enum_value;



So as long as the enum is not used in arithmetic context ie. bitwise operations (the enum is the left-hand operand) but with the streeam insertion operator I can not follow the rationale of the rule. Is this an oversight in the rule or is there a more specific reason behind this?
Reply
#2
You are correct that use of operator<< as a stream output with enum is not permitted by this rule, so your example needs a deviation.

However, we agree that the use of enums with streams should be compliant. MISRA C++:2023 allows the use of scoped enums with streams.
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
(08-12-2023, 01:17 PM)misra cpp Wrote: You are correct that use of operator<< as a stream output with enum is not permitted by this rule, so your example needs a deviation.

However, we agree that the use of enums with streams should be compliant. MISRA C++:2023 allows the use of scoped enums with streams.

Thank you for your answer and the information, good to know that it is already considered in MISRA C++:2023.
Reply


Forum Jump:


Users browsing this thread: 3 Guest(s)