Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using integer sequences with tuples and variadic templates

Let's say I have a tuple:

std::tuple<int, char, unsigned int> t{1, 'a', 4}

How do I iterate on the types of the above tuple using std::index_sequence and friends, so I can use (or re-write if needed) the function to_token below?

template<typename P1, typename... Param>
std::vector<std::string> to_token(const P1& p1, const Param&... param) {
    const auto to_token_impl = [](const auto& t) {
        using ParamType = std::decay_t<decltype(t)>;
        std::stringstream ss;

        if constexpr (std::is_same_v<ParamType, char>)
            ss << "char";
        else if constexpr (std::is_integral_v<ParamType>) {
            ss << "integral";
        }
        return ss.str();
    };
    return {to_token_impl(p1), to_token_impl(param)...};
}

Expected output: { "integral", "char", "integral" }

Based on the examples found here, I've started working on this indirection but I can't wrap my mind around what to do next...

template<typename... Args>
void tokenize(const std::tuple<Args...>& t) {
    tokenize_impl(t, std::index_sequence_for<Args...>{});
}

template<typename Tuple, std::size_t... Is>
void tokenize_impl(const Tuple& t, std::index_sequence<Is...>) {
    // ?
}
like image 224
Fluffy Avatar asked Apr 30 '26 06:04

Fluffy


1 Answers

template<typename... Args>
decltype(auto) tokenize(const std::tuple<Args...>& t) {
    return std::apply(
        [](auto const &... o) -> decltype(auto) { return to_token(o...); },
        t
    );
}

The lambda is required to defer to_token's argument deduction until it can actually take place inside of std::apply, otherwise to_token has no definite type and can't be passed as a parameter.

like image 95
Quentin Avatar answered May 01 '26 19:05

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!