I hope the subject reflects what I want to ask here ... I gave my best.
We have to set certains variables based on several run-time conditions. We always went for if..else statements but I find them too cumbersome especially given there could be several conditions. I tried to develop something using c++11/17 features and came up with the following.
So my question is with respect to: Performance, and readability, would you prefer to use the following ?
template <typename DST, typename... Ts>
void SetValue(DST& dst, Ts&&... ts)
{
CheckAndSetVal(dst, std::forward<Ts>(ts)...);
}
template <typename DST>
void CheckAndSetVal(DST&) {}
template <typename DST, typename T1, typename T2, typename... Ts>
std::enable_if_t<std::is_same_v<DST, T2> > CheckAndSetVal(DST& dst, T1&& cond, T2&& val, Ts&&... ts)
{
if (cond())
dst = val; // Assign the value here ...
else
CheckAndSetVal(dst, std::forward<Ts>(ts)...);
}
template <typename DST, typename T1, typename T2, typename... Ts>
std::enable_if_t<!std::is_same_v<DST, T2> > CheckAndSetVal(DST& dst, T1&& cond, T2&& val, Ts&&... ts)
{
if (cond())
dst = val(); // Assign the value using this functor ..
else
CheckAndSetVal(dst, std::forward<Ts>(ts)...);
}
int i;
//
// In practive though the conditions are not as trivial as they look here.
//
SetValue(i, []() { return false; }, 444
, []() { return false; }, 999
, []() { return true; }, []() { return 222; });
Aucun commentaire:
Enregistrer un commentaire