design patterns - C# style enums in C++ -
i'm trying write log library use external tool
i'm looking convenient way add key-strings output stream parsing external tool while having least impact on programmer using library
the goal achieved this:
cout << debug::verbose << "a should equal 3" << endl; cout << debug::warning << "something went wrong" << endl;
for structured data following
struct debug { static const std::string fatal_error; static const std::string error; static const std::string warning; static const std::string important; static const std::string information; static const std::string verbose; static const std::string debug; };
this works find add level of abstraction std::string
type.
in java/c# use enum
achieve write behavior, how can implement in c++ elegantly.
i think in c++ iostreams, stream manipulators in style of endl
more idiomatic:
#include <iostream> namespace debug { std::ostream & info(std::ostream & os) { return os << "info: "; } std::ostream & warn(std::ostream & os) { return os << "warning: "; } std::ostream & error(std::ostream & os) { return os << "error: "; } } int main() { std::cout << debug::info << "this main()\n" << debug::error << "everything broken\n"; }
Comments
Post a Comment