Search code examples
c++functionstdoptional

Writing functions which handle invalid inputs in C++


In C++, how to handle function outputs , if the inputs are invalid. Say, I am writing a function to multiply two matrices. How to deal with it if the two matrices cannot be multiplied (due to in-compatible shape)?

I tried to use std::optional , but then it has created other problems. Since the output is expected to be std::optional(Matrix) ,I have to write all the other functions in the class (like print Matrix()) with the expected output as std::optional , which seems unnecessary.


Solution

  • I think this could be fun. Just add a 'valid' property to the Matrix and check it only when you want to!

    class Matrix
    {
    public:
        Matrix Multiply(Matrix other)
        {
           return Multiply(other, m_isValid);
        }
    
        bool IsValid()
        {
            return m_isValid;
        }
    
    private:
        bool m_isValid;
        Matrix Multiply(Matrix other, bool& isValid);
    };