Skip to content

Add lazy function with auto inferred type #5101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/util/lazy.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,12 @@ class lazyt
}
};

/// Delay the computation of \p fun to the next time the \c force method
/// is called.
template <typename funt>
auto lazy(funt fun) -> lazyt<decltype(fun())>
{
return lazyt<decltype(fun())>::from_fun(std::move(fun));
}

#endif // CPROVER_UTIL_LAZY_H
21 changes: 20 additions & 1 deletion unit/util/lazy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Author: Romain Brenguier, [email protected]
#include <testing-utils/use_catch.h>
#include <util/lazy.h>

SCENARIO("lazy test", "[core][util][lazy]")
SCENARIO("lazyt::from_fun test", "[core][util][lazy]")
{
std::size_t call_counter = 0;
auto length_with_counter = [&call_counter](const std::string &s) {
Expand All @@ -27,3 +27,22 @@ SCENARIO("lazy test", "[core][util][lazy]")
REQUIRE(call_counter == 1);
REQUIRE(result == 3);
}

SCENARIO("lazy test", "[core][util][lazy]")
{
std::size_t call_counter = 0;
auto length_with_counter = [&call_counter](const std::string &s) {
++call_counter;
return s.length();
};
lazyt<std::size_t> lazy_length =
lazy([&] { return length_with_counter("foobar"); });

REQUIRE(call_counter == 0);
auto result = lazy_length.force();
REQUIRE(call_counter == 1);
REQUIRE(result == 6);
result = lazy_length.force();
REQUIRE(call_counter == 1);
REQUIRE(result == 6);
}