LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Programs · Question 5

Retry helper that takes an operation as a lambda in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write a function template retry(attempts, op, on_fail) that calls a lambda until it succeeds or attempts run out, calling another lambda on each failure; simulate a flaky network call.

Solution
main.cpp
#include <iostream>
#include <optional>
#include <string>

template <typename Op, typename OnFail>
auto retry(int attempts, Op op, OnFail on_fail) -> decltype(op()) {
    for (int i = 1; i <= attempts; ++i) {
        if (auto result = op()) return result;
        on_fail(i);
    }
    return std::nullopt;
}

int main() {
    int calls = 0;
    auto flaky_fetch = [&calls]() -> std::optional<std::string> {
        ++calls;
        if (calls < 3) return std::nullopt;          // fails twice, then works
        return "200 OK";
    };
    auto log = [](int attempt) { std::cout << "attempt " << attempt << " failed\n"; };

    auto r1 = retry(5, flaky_fetch, log);
    std::cout << r1.value_or("gave up") << " after " << calls << " calls\n";

    auto r2 = retry(2, [] { return std::optional<std::string>{}; }, log);
    std::cout << r2.value_or("gave up") << '\n';
    return 0;
}

Output Verified by compiling and running

attempt 1 failed
attempt 2 failed
200 OK after 3 calls
attempt 1 failed
attempt 2 failed
gave up

retry knows nothing about networking: the operation and the failure handler are passed in as lambdas. The flaky lambda keeps its call count through a reference capture.

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