Advertisement
Jakowlew

Capturing-lambda-to-function-pointer cast

Feb 11th, 2019
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <type_traits>
  4. #include <utility>
  5.  
  6. template <typename F>
  7. struct lambda_traits : lambda_traits<decltype(&F::operator())> {};
  8.  
  9. template <typename F, typename R, typename... Args>
  10. struct lambda_traits<R(F::*)(Args...)> {
  11.     using ptr_t = std::add_pointer_t<R(Args...)>;
  12.  
  13.     static inline ptr_t to_fptr(F&& f) {
  14.         static F fn = std::forward<F>(f);
  15.         return [](Args... args) {
  16.             return fn(std::forward<Args>(args)...);
  17.         };
  18.     }
  19. };
  20.  
  21. template <typename F, typename R, typename... Args>
  22. struct lambda_traits<R(F::*)(Args...) noexcept>
  23. {
  24.     using ptr_t = std::add_pointer_t<R(Args...)>;
  25.  
  26.     static inline auto to_fptr(F&& f) -> ptr_t {
  27.         static F fn = std::forward<F>(f);
  28.         return [](Args... args) {
  29.             return fn(std::forward<Args>(args)...);
  30.         };
  31.     }
  32. };
  33.  
  34. template <typename F, typename R, typename... Args>
  35. struct lambda_traits<R(F::*)(Args...) const>
  36. {
  37.     using ptr_t = std::add_pointer_t<R(Args...)>;
  38.  
  39.     static inline auto to_fptr(F&& f) -> ptr_t {
  40.         static F fn = std::forward<F>(f);
  41.         return [](Args... args) {
  42.             return fn(std::forward<Args>(args)...);
  43.         };
  44.     }
  45. };
  46.  
  47. template <typename F, typename R, typename... Args>
  48. struct lambda_traits<R(F::*)(Args...) const noexcept>
  49. {
  50.     using ptr_t = std::add_pointer_t<R(Args...)>;
  51.  
  52.     static inline auto to_fptr(F&& f) -> ptr_t {
  53.         static F fn = std::forward<F>(f);
  54.         return [](Args... args) {
  55.             return fn(std::forward<Args>(args)...);
  56.         };
  57.     }
  58. };
  59.  
  60. template <class F>
  61. inline auto to_fptr(F&& f) {
  62.     return lambda_traits<F>::to_fptr(std::forward<F>(f));
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement