vtr*_*trz 15 c++ stl c++17 stdoptional
是否有可能以std::optional::value_or(expr)懒惰的方式评估参数,所以expr仅在没有值的情况下计算?
如果没有,什么是适当的替代品?
Pio*_*cki 23
#include <optional>
template <typename F>
struct Lazy
{
F f;
operator decltype(f())() const
{
return f();
}
};
template <typename F>
Lazy(F f) -> Lazy<F>;
int main()
{
std::optional<int> o;
int i = o.value_or(Lazy{[]{return 0;}});
}
Run Code Online (Sandbox Code Playgroud)
您可以编写辅助函数:
template<typename T, typename F>
T lazy_value_or(const std::optional<T> &opt, F fn) {
if(opt) return opt.value();
return fn();
}
Run Code Online (Sandbox Code Playgroud)
然后可以用作:
T t = lazy_value_or(opt, [] { return expensive_computation();});
Run Code Online (Sandbox Code Playgroud)
如果这明显少于明确的打字,那么由你来判断; 仍然,你可以用宏来缩短它:
#define LAZY_VALUE_OR(opt, expr) \
lazy_value_or((opt), [&] { return (expr);})
Run Code Online (Sandbox Code Playgroud)
用作
T t = LAZY_VALUE_OR(opt, expensive_calculation());
Run Code Online (Sandbox Code Playgroud)
这是我认为你想要的最接近的,但可能会因为它隐藏了太多东西而感到不满.