我喜欢在我的 C++ 代码中使用 std::experimental::optional,但问题是 value_or 要求默认值与可选值的类型相同。
当我想要一个包含 int 或包含错误消息的可选项时,这不能很好地工作。
Result<T, E>
我想我可以使用一个带有布尔值的联合结构来指示该值是否存在或者它是一个错误,但如果 C++ 只是具有像 Rust 这样的类型肯定会很好。
有没有这样的类型?为什么Boost没有实现它?
Result 确实比 Option 有用得多,而且 Boost 的人肯定知道它的存在。也许我会去阅读 Rust 实现,然后将其复制到 C++?
前任:
// Function either returns a file descriptor for a listening socket or fails
// and returns a nullopt value.
// My issue: error messages are distributed via perror.
std::experimental::optional<int> get_tcp_listener(const char *ip_and_port);
// You can use value_or to handle error, but the error message isn't included!
// I have to write my own error logger that is contained within
// get_tcp_listener. I would really appreciate if it returned the error
// message on failure, rather than an error value.
int fd = get_tcp_listener("127.0.0.1:9123").value_or(-1);
// Rust has a type which does what I'm talking about:
let fd = match get_tcp_listener("127.0.0.1:9123") {
Ok(fd) => fd,
Err(msg) => { log_error(msg); return; },
}