Index: llvm/trunk/include/llvm/ADT/STLExtras.h =================================================================== --- llvm/trunk/include/llvm/ADT/STLExtras.h +++ llvm/trunk/include/llvm/ADT/STLExtras.h @@ -24,6 +24,7 @@ #include #include #include +#include #include // for std::pair #include "llvm/ADT/Optional.h" @@ -690,6 +691,28 @@ return detail::enumerator_impl(std::forward(Range)); } +namespace detail { +template +auto apply_impl(F &&f, Tuple &&t, index_sequence) + -> decltype(std::forward(f)(std::get(std::forward(t))...)) { + return std::forward(f)(std::get(std::forward(t))...); +} +} + +/// Given an input tuple (a1, a2, ..., an), pass the arguments of the +/// tuple variadically to f as if by calling f(a1, a2, ..., an) and +/// return the result. +template +auto apply(F &&f, Tuple &&t) -> decltype(detail::apply_impl( + std::forward(f), std::forward(t), + build_index_impl< + std::tuple_size::type>::value>{})) { + using Indices = build_index_impl< + std::tuple_size::type>::value>; + + return detail::apply_impl(std::forward(f), std::forward(t), + Indices{}); +} } // End llvm namespace #endif Index: llvm/trunk/unittests/ADT/STLExtrasTest.cpp =================================================================== --- llvm/trunk/unittests/ADT/STLExtrasTest.cpp +++ llvm/trunk/unittests/ADT/STLExtrasTest.cpp @@ -192,4 +192,49 @@ EXPECT_EQ(0, Moves); EXPECT_EQ(0, Destructors); } + +TEST(STLExtrasTest, ApplyTuple) { + auto T = std::make_tuple(1, 3, 7); + auto U = llvm::apply( + [](int A, int B, int C) { return std::make_tuple(A - B, B - C, C - A); }, + T); + + EXPECT_EQ(-2, std::get<0>(U)); + EXPECT_EQ(-4, std::get<1>(U)); + EXPECT_EQ(6, std::get<2>(U)); + + auto V = llvm::apply( + [](int A, int B, int C) { + return std::make_tuple(std::make_pair(A, char('A' + A)), + std::make_pair(B, char('A' + B)), + std::make_pair(C, char('A' + C))); + }, + T); + + EXPECT_EQ(std::make_pair(1, 'B'), std::get<0>(V)); + EXPECT_EQ(std::make_pair(3, 'D'), std::get<1>(V)); + EXPECT_EQ(std::make_pair(7, 'H'), std::get<2>(V)); +} + +class apply_variadic { + static int apply_one(int X) { return X + 1; } + static char apply_one(char C) { return C + 1; } + static StringRef apply_one(StringRef S) { return S.drop_back(); } + +public: + template + auto operator()(Ts &&... Items) + -> decltype(std::make_tuple(apply_one(Items)...)) { + return std::make_tuple(apply_one(Items)...); + } +}; + +TEST(STLExtrasTest, ApplyTupleVariadic) { + auto Items = std::make_tuple(1, llvm::StringRef("Test"), 'X'); + auto Values = apply(apply_variadic(), Items); + + EXPECT_EQ(2, std::get<0>(Values)); + EXPECT_EQ("Tes", std::get<1>(Values)); + EXPECT_EQ('Y', std::get<2>(Values)); +} }