Add `lazy` function with auto inferred type

This allow to write `lazy(f)` and get the type of the object
automatically inferred from the type of `f`.
This commit is contained in:
Romain Brenguier 2019-09-09 07:23:19 +01:00
parent 1b4de4297b
commit d5e6b59311
2 changed files with 28 additions and 1 deletions

View File

@ -43,4 +43,12 @@ private:
}
};
/// 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

View File

@ -9,7 +9,7 @@ Author: Romain Brenguier, romain.brenguier@diffblue.com
#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) {
@ -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);
}