LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 13

Chaining std::expected with and_then and transform Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <expected>
#include <iostream>
#include <string>

std::expected<int, std::string> to_int(const std::string& s) {
    if (s.empty() || s.find_first_not_of("0123456789") != std::string::npos) return std::unexpected("bad number: '" + s + "'");
    return std::stoi(s);
}
std::expected<int, std::string> safe_div(int a, int b) {
    if (b == 0) return std::unexpected(std::string("division by zero"));
    return a / b;
}

int main() {
    for (auto [a, b] : {std::pair{"84", "4"}, {"84", "0"}, {"8x", "2"}}) {
        auto r = to_int(a).and_then([&](int x) { return to_int(b).and_then([x](int y) { return safe_div(x, y); }); })
                          .transform([](int q) { return q * 10; });
        std::cout << (r ? std::to_string(*r) : r.error()) << '\n';
    }
    return 0;
}
  • A 210 division by zero bad number: '8x' Correct
  • B 21 division by zero bad number: '8x'
  • C 210 0 0
  • D 210 division by zero bad number: '2'
Correct Answer: Option A

and_then continues only with a value; the first error short-circuits the chain and is carried to the end. transform changes only successful values.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links