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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!