I have a piece of c++11 code similar like below:
switch(var) {
case 1: dosomething(std::get<1>(tuple));
case 2: dosomething(std::get<2>(tup
Here's an unreadably over-generic implementation without recursion. I don't think I'd use this in production - it's a good example of write-only code - but it's interesting that it can be done. (DEMO):
#include
#include
#include
#include
#include
#include
#include
template struct index_sequence {};
template
struct build : public build {};
template
struct build<0, Is...> {
using type = index_sequence;
};
template
using make_index_sequence = typename build::type;
template
using remove_reference_t = typename std::remove_reference::type;
namespace detail {
template
void tuple_switch(const std::size_t i, Tuple&& t, F&& f, index_sequence) {
[](...){}(
(i == Is && (
(void)std::forward(f)(std::get(std::forward(t))), false))...
);
}
} // namespace detail
template
void tuple_switch(const std::size_t i, Tuple&& t, F&& f) {
static constexpr auto N =
std::tuple_size>::value;
detail::tuple_switch(i, std::forward(t), std::forward(f),
make_index_sequence{});
}
constexpr struct {
template
void operator()(const T& t) const {
std::cout << t << '\n';
}
} print{};
int main() {
{
auto const t = std::make_tuple(42, 'z', 3.14, 13, 0, "Hello, World!");
for (std::size_t i = 0; i < std::tuple_size::value; ++i) {
tuple_switch(i, t, print);
}
}
std::cout << '\n';
{
auto const t = std::array{{0,1,2,3}};
for (std::size_t i = 0; i < t.size(); ++i) {
tuple_switch(i, t, print);
}
}
}