链式调用,是从别的语言学的(函数式编程),也不是Rust首创的。
C++也能用链式调用,
1、通过std::ranges的管道符|
std::vector<int> numbers = {1, 5, 3, 8, 2, 7};
for (int n : numbers
| std::views::filter([](int n){ return n % 2 == 0; })
| std::views::transform([](int n){ return n * n; }))
{
std::cout << n << " ";
}
2、通过std::expected或者tl::expected(后者是学的Rust)
tl::expected<int, std::string> parse_int(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return tl::unexpected("not a number");
}
}
int main() {
auto result = parse_int("123")
.map([](int n){ return n * 2; })
.map([](int n){ return n + 1; })
.and_then([](int n){
if (n > 100) return tl::expected<int, std::string>{n};
else return tl::make_unexpected(std::string{"too small"});
});
std::expected<int, std::string> parse_int(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::unexpected("not a number");
}
}
int main() {
auto result = parse_int("123")
.transform([](int n){ return n * 2; }) // C++23 用 transform
.transform([](int n){ return n + 1; })
.and_then([](int n){
if (n > 100) return std::expected<int, std::string>{n};
else return std::unexpected("too small");
});
3、自己撸,主要是要求class的每个成员函数最后都返回*this。
--
FROM 61.48.128.*