Skip to content

Instantly share code, notes, and snippets.

@skmp
Last active January 16, 2018 06:00
Show Gist options
  • Save skmp/b62f0968503d66b1cc6b to your computer and use it in GitHub Desktop.
Save skmp/b62f0968503d66b1cc6b to your computer and use it in GitHub Desktop.
//Example code for http://stackoverflow.com/questions/32025355/detect-if-c-lambda-can-be-converted-to-function-pointer
//Makes use of (adapted) remove_class from http://stackoverflow.com/questions/11893141/inferring-the-call-signature-of-a-lambda-or-arbitrary-callable-for-make-functio/12283159#12283159
#include <utility>
template<typename T> struct remove_class_ref { };
template<typename C, typename R, typename... A>
struct remove_class_ref<R(C::*)(A...)> { using type = R(*&)(A...); };
template<typename C, typename R, typename... A>
struct remove_class_ref<R(C::*)(A...) const> { using type = R(*&)(A...); };
template<typename C, typename R, typename... A>
struct remove_class_ref<R(C::*)(A...) volatile> { using type = R(*&)(A...); };
template<typename C, typename R, typename... A>
struct remove_class_ref<R(C::*)(A...) const volatile> { using type = R(*&)(A...); };
template<class C>
struct call_lambda_i {
//[...]
typedef typename remove_class_ref<decltype(&C::operator())>::type fun_ref_t;
static const bool is_static = std::is_assignable<fun_ref_t, C>::value;
//[...]
};
int main() {
auto x = []{ return 5; };
auto y = [x]{ return x(); };
static_assert(call_lambda_i<decltype(x)>::is_static, "non-catpure should convert");
static_assert(!call_lambda_i<decltype(y)>::is_static, "catpure should not convert");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment