Created
May 19, 2015 01:05
-
-
Save elbeno/cfe76f1ccbc8c6c30871 to your computer and use it in GitHub Desktop.
A macro for constexpr lambdas in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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