Last active
August 7, 2023 07:37
-
-
Save sudoLife/a9b5848a18a3c2b28636c85b85c2f178 to your computer and use it in GitHub Desktop.
A C++ status variable class that throws when there is a status code indicating a problem.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The status_variable class is a templated class that is used to handle the status | |
// of a variable with a predefined success code. Any assignment to this variable | |
// that does not match the success code results in an exception being thrown. | |
template <typename T> | |
class status_variable | |
{ | |
public: | |
status_variable() = default; | |
explicit status_variable(int success_code) : success_code(success_code) {} | |
void operator=(T other) | |
{ | |
if (other != success_code) | |
{ | |
throw std::runtime_error(fmt::format("Error in status, expected value {}, got {}", success_code, other)); | |
} | |
} | |
private: | |
T success_code = 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example usage is like so:
The whole thing is useful if you have a bunch of similar calls with the same success status code, and you don't want to try and catch each and every one of them separately.