Skip to content

Instantly share code, notes, and snippets.

@SammyJames
Created February 22, 2017 23:17
Show Gist options
  • Save SammyJames/8816676240220a8519fd15683cccc1ec to your computer and use it in GitHub Desktop.
Save SammyJames/8816676240220a8519fd15683cccc1ec to your computer and use it in GitHub Desktop.
a simple implementation of tuple via lambda.
#include <iostream>
using namespace std;
template <typename Storage>
struct LambdaTuple
{
explicit constexpr LambdaTuple(Storage&& aStorage)
: m_storage(move(aStorage))
{
}
size_t Length() const
{
return m_storage([](auto... args) { return sizeof...(args); });
}
template <typename UnaryFunc, typename... Args>
decltype(auto) ApplyAfter(UnaryFunc&& aFunc, Args&&... inArgs) const
{
return m_storage([=](auto... args) { return (aFunc)(inArgs..., args...); });
}
template <typename UnaryFunc, typename... Args>
decltype(auto) ApplyBefore(UnaryFunc&& aFunc, Args&&... inArgs) const
{
return m_storage([=](auto... args) { return (aFunc)(args..., inArgs...); });
}
template <typename UnaryFunc>
decltype(auto) Apply(UnaryFunc&& aFunc) const
{
return m_storage([=](auto... args) { return (aFunc)(args...); });
}
Storage m_storage;
};
template <typename... Args>
decltype(auto) MakeLambdaTuple(Args&&... inArgs)
{
auto storage = [=](auto functor) -> decltype(auto) { return functor(inArgs...); };
return LambdaTuple<decltype(storage)>{move(storage)};
}
static bool test_func(bool, int, const char*, float)
{
return true;
}
int main()
{
auto tuple = MakeLambdaTuple(1, "4", 3.f);
bool ret = tuple.ApplyAfter(&test_func, true);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment