MISRA Discussion Forums
A4-5-1 with overloading operator<< - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: AUTOSAR C++:2014 rules (https://forum.misra.org.uk/forumdisplay.php?fid=185)
+--- Thread: A4-5-1 with overloading operator<< (/showthread.php?tid=1664)



A4-5-1 with overloading operator<< - Jakob Klein - 07-11-2023

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?


RE: A4-5-1 with overloading operator<< - misra cpp - 08-12-2023

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.


RE: A4-5-1 with overloading operator<< - Jakob Klein - 12-12-2023

(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.