Last active
March 21, 2024 06:19
-
-
Save khvorov/cd626ea3685fd5e8bf14 to your computer and use it in GitHub Desktop.
Convert lambda to std::function
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
// g++ prog.cc -Wall -Wextra -O2 -march=native -std=gnu++1y | |
#include <cxxabi.h> | |
#include <algorithm> | |
#include <functional> | |
#include <iostream> | |
#include <typeinfo> | |
namespace detail | |
{ | |
template <typename F> | |
struct function_traits : public function_traits<decltype(&F::operator())> {}; | |
template <typename R, typename C, typename... Args> | |
struct function_traits<R (C::*)(Args...) const> | |
{ | |
using function_type = std::function<R (Args...)>; | |
}; | |
} | |
template <typename F> | |
using function_type_t = typename detail::function_traits<F>::function_type; | |
template <typename F> | |
function_type_t<F> to_function(F & lambda) | |
{ | |
return static_cast<function_type_t<F>>(lambda); | |
} | |
template <typename T> | |
std::string type_id(const T & t) | |
{ | |
int status = 0; | |
char * tmp = abi::__cxa_demangle(typeid(t).name(), 0, 0, &status); | |
std::string result(tmp); | |
free(tmp); | |
return std::move(result); | |
}; | |
int main(int argc, char const *argv[]) | |
{ | |
auto lambda = [argc, &argv]() | |
{ | |
std::for_each(argv, argv + argc, | |
[](const char * arg) | |
{ | |
std::cout << arg << std::endl; | |
}); | |
}; | |
// convert lambda to std::function | |
auto f = to_function(lambda); | |
std::cout << type_id(lambda) << std::endl; | |
std::cout << type_id(f) << std::endl; | |
// convert std::function to std::function | |
to_function(f)(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment