C++ call function with many different types
With some boiler-plate to obtain a tuple foreach, you can implement what you want as follows:
#include <tuple>
#include <utility>
namespace detail
{
template<typename T, typename F, std::size_t... Is>
void for_each(T&& t, F f, std::index_sequence<Is...>)
{
( static_cast<void>(f(std::get<Is>(std::forward<T>(t)))),... );
}
}
template<typename... Ts, typename F>
void for_each_in_tuple(std::tuple<Ts...> const& t, F f)
{
detail::for_each(t, f, std::index_sequence_for<Ts...>{});
}
int main() {
std::tuple<uint8_t, uint16_t, double> tup{};
for_each_in_tuple(tup, [](auto&& arg) {
doSomething(arg);
});
}
Live Example
If you want to have a predefined sequence of types you can use TypeList aproach if you don't want to create tuples with arguments:
#include <type_traits>
#include <utility>
void doSomething(int)
{
}
void doSomething(double)
{
}
template <typename... Args>
void doSomething(Args&&... args)
{
(doSomething(std::forward<Args>(args)), ...);
}
template <typename ...Args>
struct TypeList{};
template <typename T>
struct DoSomethingHelper;
template <typename ...Args>
struct DoSomethingHelper<TypeList<Args...>>
{
static void doSomething(Args&&... args)
{
::doSomething(std::forward<Args>(args)...);
}
};
template <typename T, typename ...Args>
void doSomethingForTypes(Args&&... args)
{
DoSomethingHelper<T>::doSomething(std::forward<Args>(args)...);
}
int main()
{
using MyTypeList = TypeList<int, double, int>;
doSomethingForTypes<MyTypeList>(1, 1.0, 2);
}
With std::tuple
and std::apply
std::tuple<uint8_t, uint16_t, double> tup{};
std::apply([](const auto&... arg) { (doSomething(arg), ...); }, tup);