Created
April 12, 2016 03:10
-
-
Save dnmiller/dc3c45bc569909b98ac6ada1b616afcc to your computer and use it in GitHub Desktop.
Basic demo for std::error_code
This file contains 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
// Taken from http://stackoverflow.com/questions/11973798/comparing-an-error-code-enum-with-stderror-code | |
#include <iostream> | |
using namespace std; | |
#include <system_error> | |
#include <cassert> | |
namespace mylib | |
{ | |
namespace errc { | |
enum my_error | |
{ | |
failed = 0 | |
}; | |
inline const char* error_message(int c) | |
{ | |
static const char* err_msg[] = | |
{ | |
"Failed", | |
}; | |
assert(c < sizeof(err_msg) / sizeof(err_msg[0])); | |
return err_msg[c]; | |
} | |
class my_error_category : public std::error_category | |
{ | |
public: | |
my_error_category() | |
{ } | |
std::string message(int c) const | |
{ | |
return error_message(c); | |
} | |
const char* name() const { return "My Error Category"; } | |
const static error_category& get() | |
{ | |
const static my_error_category category_const; | |
return category_const; | |
} | |
}; | |
inline std::error_code make_error_code(my_error e) | |
{ | |
return std::error_code(static_cast<int>(e), my_error_category::get()); | |
} | |
} // end namespace errc | |
} // end namespace mylib | |
namespace std { | |
template<> | |
struct is_error_code_enum<mylib::errc::my_error> | |
: std::true_type | |
{ }; | |
} // end namespace std | |
int main() | |
{ | |
std::error_code ec1 = mylib::errc::make_error_code(mylib::errc::failed); // works | |
std::error_code ec2 = mylib::errc::failed; // works | |
bool result = (ec2 == mylib::errc::failed); // works | |
std::cout << ec1 << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment