Twitterでおもしろい方法を教えてもらいました。
@cpp_akira横からですが、operator optional<T>()を定義したラッパーを作って、それを返したらどうでしょうか。URL 2011-09-07 02:12:29 via V2C to @cpp_akira |
ErrorCodeの単純なラッパークラスを作り、boost::optionalへの型変換演算子を用意することで、
boost::optional
#include <iostream> #include <string> #include <boost/optional.hpp> struct ErrorCode { enum enum_t { FileNotFound }; }; std::string to_string(ErrorCode::enum_t error) { switch (error) { case ErrorCode::FileNotFound: return "File Not Found"; } assert(false); } template <class T> class error { boost::optional<T> value; public: error() {} error(T value) : value(value) {} operator boost::optional<T>() const { return value; } }; error<ErrorCode::enum_t> FileOpen() { return ErrorCode::FileNotFound; } int main() { if (boost::optional<ErrorCode::enum_t> error = FileOpen()) { std::cout << to_string(error.get()) << std::endl; } /* if (FileOpen()) { // コンパイルエラー!boolに変換できない std::cout << "file open error" << std::endl; } */ }
FileNotFound
これはすばらしいですね。