Skip to content

Instantly share code, notes, and snippets.

@elbeno
Created May 19, 2015 01:05
Show Gist options
  • Save elbeno/cfe76f1ccbc8c6c30871 to your computer and use it in GitHub Desktop.
Save elbeno/cfe76f1ccbc8c6c30871 to your computer and use it in GitHub Desktop.
A macro for constexpr lambdas in C++
#include <iostream>
#include <type_traits>
#include <utility>
template<class F>
struct wrapper
{
static_assert(std::is_empty<F>(), "Lambdas must be empty");
template<class... Ts>
decltype(auto) operator()(Ts&&... xs) const
{
return reinterpret_cast<const F&>(*this)(std::forward<Ts>(xs)...);
}
};
struct wrapper_factor
{
template<class F>
constexpr wrapper<F> operator += (F*)
{
return {};
}
};
struct addr_add
{
template<class T>
friend typename std::remove_reference<T>::type *operator+(addr_add, T &&t)
{
return &t;
}
};
#define STATIC_LAMBDA wrapper_factor() += true ? nullptr : addr_add() + []
const constexpr auto add_one = STATIC_LAMBDA(auto x)
{
return x + 1;
};
int main(void)
{
// Produces 2
std::cout << add_one(1) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment