How to call a template function for each type in a typelist with arguments (e.g. another tuple)?
Given is a typelist std::tuple<T1, T2, T3, ...>
and a std::tuple
containing data.
template <typename T>
void doSomething (const auto& arg) {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
template <typename T> struct w {T v; w(T _v) : v{_v} {}};
int main () {
using types = std::tuple<int, char, float, double, w<int>, w<float>>; // used as type list
constexpr auto data = std::make_tuple(1, 2, 3.0, 4.0f, w(5.0));
// call doSomething<T>(data) for each type in types
// like
// someFunctor<types>(doSomething, data);
}
My current idea is a functor like appreach that receives the typelist to extract nexted types and std::tuple<Ts>
having an operator ()
to call doSomething<T>(args)
for each of Ts.
template<template<typename...> typename TL, typename... Ts>
struct someFunctor {
template<typename... Args>
static constexpr void operator() (Args&&... args) {
(doSomething<Ts>(std::forward<Args>(args)...), ...);
}
};
Not sure if that's the smartest approach. Brain fog blocked me so far to get it work.
someFunctor<types>(doSomething, data);
instead ofsomeFunctor(doSomething, data);
? – Bunchyconst auto &
indoSomething
intended, or was it supposed to beconst T &
? – MemnondoSomething
to be called for each type intypes
once witharg
being a reference todata
each time? – BunchydoSomething<int>(data); doSomething<char>(data); doSomething<w<int>>(data); ...
– Somethingoperator()
explicitly with template arguments. – Bunchy