PS
Size: a a a
PS
PS
VK
VK
PS
ПК
PS
АК
template <class... Ts>
auto foo(const Ts& ...ts) {
// [i] - псевдокод
if (Predicate(ts[0])) return F(ts[0]);
if (Predicate(ts[1])) return F(ts[1]);
...
if (Predicate(ts[sizeof...(Ts) - 1])) return F(ts[sizeof...(Ts) - 1]);
return smth_default;
}
АК
std::optional<..> result;
, что не очень устраиваетЕ
template <class... Ts>
auto foo(const Ts& ...ts) {
// [i] - псевдокод
if (Predicate(ts[0])) return F(ts[0]);
if (Predicate(ts[1])) return F(ts[1]);
...
if (Predicate(ts[sizeof...(Ts) - 1])) return F(ts[sizeof...(Ts) - 1]);
return smth_default;
}
OZ
template <class... Ts>
auto foo(const Ts& ...ts) {
// [i] - псевдокод
if (Predicate(ts[0])) return F(ts[0]);
if (Predicate(ts[1])) return F(ts[1]);
...
if (Predicate(ts[sizeof...(Ts) - 1])) return F(ts[sizeof...(Ts) - 1]);
return smth_default;
}
std::index_sequence
+ lambda?АК
std::index_sequence
+ lambda?АК
Е
АК
АК
template <class T> constexpr bool Predicate(const T& value) { return value > 0; }Predicate и F глобальные для упрощения. Задача - сделать без рекурсии
template <class T> constexpr auto F(const T& value) { return sizeof(T); }
template <class T, class... Ts>
constexpr auto foo(const T& t, const Ts& ...ts) {
if (Predicate(t)) return F(t);
if constexpr (sizeof...(ts) > 0) {
return foo(ts...);
}
// UB here
}
static_assert(foo(-1, -1.0f, 10, true) == sizeof(int));
АК
#include <optional>
template <class... Ts>
constexpr auto foo2(const Ts& ...ts) {
std::optional<decltype(F(0))> result;
auto l = [&](const auto& t) {
if (!result && Predicate(t))
result = F(t);
};
(l(ts), ...);
return result.value();
}
ПК
template <class T> constexpr bool Predicate(const T& value) { return value > 0; }Predicate и F глобальные для упрощения. Задача - сделать без рекурсии
template <class T> constexpr auto F(const T& value) { return sizeof(T); }
template <class T, class... Ts>
constexpr auto foo(const T& t, const Ts& ...ts) {
if (Predicate(t)) return F(t);
if constexpr (sizeof...(ts) > 0) {
return foo(ts...);
}
// UB here
}
static_assert(foo(-1, -1.0f, 10, true) == sizeof(int));
template <typename T, typename R>
void if_template(const T& t, R& return_slot, bool& go_next) {
if (go_next && Predicate(t)) { return_slot = F(t); go_next = false; }
}
template <class... Ts>
constexpr auto foo(const Ts& ...ts) {
some_deduced_type return_slot;
bool go_next = true;
if_template(ts, return_slot, go_next), ...;
return return_slot;
}
some_deduced_type
, ну и у него появилось требование default-constructibleАК
template <typename T, typename R>
void if_template(const T& t, R& return_slot, bool& go_next) {
if (go_next && Predicate(t)) { return_slot = F(t); go_next = false; }
}
template <class... Ts>
constexpr auto foo(const Ts& ...ts) {
some_deduced_type return_slot;
bool go_next = true;
if_template(ts, return_slot, go_next), ...;
return return_slot;
}
some_deduced_type
, ну и у него появилось требование default-constructible