こんな関数があったとして、「空入力でエラーになった」「禁止されている値を入力した」等の、複数のエラーを返す設計はどうすればいいかと考えて、
bool valid_check(const std::string& input);
こうすることにした。
#include <cctype> #include <boost/optional.hpp> #include <boost/range.hpp> template <class InputIterator, class Pred> bool all_of(InputIterator first, InputIterator last, Pred pred) { for (; first != last; ++first) { if (!pred(*first)) return false; } return true; } template <class InputRange, class Pred> bool all_of(const InputRange& r, Pred pred) { return all_of(boost::begin(r), boost::end(r), pred); } struct error_value { enum enum_t { empty, // 空入力された not_number // 数値以外が入力された }; }; boost::optional<error_value::enum_t> valid_check(const std::string& input) { if (input.empty()) return error_value::empty; if (!all_of(input, std::isdigit)) return error_value::not_number; return boost::none; } int main() { const std::string input = "123"; if (boost::optional<error_value::enum_t> error = valid_check(input)) { error_value::enum_t value = error.get(); return 1; } }