I have a template taking a type that is structurally-bindable to two aliases (could be a tuple but also a struct). I need the type of those two variables the aliases point to.
template <typename T>
T obj;
// type of a/b in auto&& [a, b] = obj ?
I need to know the type before I actually use the structured binding:
template <typename S>
void fn(ranges::any_view<S> range_of_tuple_or_struct_or_pair) {
last_from = std::numeric_limits<?????>::max();
// ????? should be the type of from (or to, they should be the same types) of:
// auto&& [from, to] = <range element>
for (auto&& [from, to] : range_of_tuple_or_struct_or_pair) {
if (from != last_from) {
...;
last_from = from;
}
}
}
I think you can do something like this:
#include <type_traits>
template <typename T, typename U>
struct Identity {
using type_first = T;
using type_second = U;
};
template <typename T>
constexpr auto GetTypes(const T& obj) noexcept {
const auto& [x, y] = obj;
return Identity<std::remove_cv_t<decltype(x)>,
std::remove_cv_t<decltype(y)>>{};
}
template <typename T>
void foo(T obj) {
// T is structurally-bindable with two fields
constexpr auto Types = GetTypes(obj);
using t1 = typename decltype(Types)::type_first;
using t2 = typename decltype(Types)::type_second;
// t1 is the first type
// t2 is the second type
}
Complete Example Here
Note that with constexpr
there is no overhead, even without enabling optimizations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With