📜 ⬆️ ⬇️

Lazy calculations in c ++ 0x, test new features

Hello. And especially to those who write on the pros and are interested in future changes in the language.
To study the features of the C ++ standard, I did a funny thing - a function to turn a simple functor into a lazy one. Those. calculated no more than once, and only at the first reference.
To use, you need a simple functor, with no arguments, to return a value.
Apply calc_once (some_func) to it - and it becomes lazy.

auto my_func = calc_once([]{ return SomeHugeCalculation(); });
if ((my_func() && some_case) || (!my_func() && some_other_case))
{
}


* This source code was highlighted with Source Code Highlighter .


Under the code, there is auto, and decltype, and lambda.
')
UPD. Thanks for the karma. Transferred to C ++ blog.


#include <boost/optional.hpp>

// - ( )
//: auto my_func = calc_once([]{ return SomeHugeCalculation(); });

template<typename LambdaFunc, typename result_type>
class calc_once_func
{
public :
calc_once_func(LambdaFunc func) : func_(func) {}
result_type operator ()()
{
return val_.is_initialized() ? val_. get () : (val_ = func_()). get ();
};
private :
boost::optional<result_type> val_;
LambdaFunc func_;
};

template<typename LambdaFunc>
auto calc_once(LambdaFunc func) -> calc_once_func<LambdaFunc, decltype(func())>
{
return calc_once_func<LambdaFunc, decltype(func())>(func);
}


* This source code was highlighted with Source Code Highlighter .

Source: https://habr.com/ru/post/85718/


All Articles