c++functionassertiostream

How could I implement an assert function that support iostream


I would like to implement a CHECK() function that can work like this:

int a = 1;
int b = 2;
int c = 1;

CHECK(a == b) << "check failed" << endl; // this will abort the program and print "check failed"
CHECK(a == c) << "check failed" << endl; // this will do nothing since CHECK is valid

I do not know how could I abort the program but still print out something. Do you know how to implement some function that works like this?


Solution

  • Completing @DominikKaszewski 's answer

    Final code is:

    class check {
    public:
        explicit check(bool success) : success{ success } {}
    
        ~check() {
            if (!success) {
                abort_with_message(s.str());
            }
        } 
    
        check(const check&) = delete;
        check(check&&) = default;
        check& operator=(const check&) = delete;
        check& operator=(check&&) = delete;
    
        template <typename T>
        check&& operator<<(const T& value) && {
            if (!success) {
                s << value;
            }
            return std::move(*this);
        }
    
        check&& operator<<(std::ostream& (*manip)(std::ostream&)) && {
            if (!success) {
                manip(s);
            }
            return std::move(*this);
        }
    
    private:
        bool success{};
        std::stringstream s{};
    };
    
    #define CHECK(predicate) (predicate) ? check{ true } : check{ false }
    

    Demo