fork download
  1. #include <type_traits>
  2. #include <memory>
  3. #include <iostream>
  4.  
  5. template <typename L, typename R, typename... Args>
  6. struct LambdaWrapper {
  7. static void set(const L& lambda) { m_l.reset(new L(lambda)); }
  8. static R callback(Args&& ... args) { return (*m_l)(std::forward<Args>(args)...); }
  9.  
  10. private:
  11. static std::unique_ptr<L> m_l;
  12. };
  13.  
  14. template <typename L, typename R, typename... Args>
  15. std::unique_ptr<L> LambdaWrapper<L, R, Args...>::m_l;
  16.  
  17. template <typename L, typename R, typename... Args>
  18. auto mem_func_to_wrapper(R (L::*)(Args...))
  19. -> LambdaWrapper<L, R, Args...>; // undefined!
  20.  
  21. template <typename L, typename R, typename... Args>
  22. auto mem_func_to_wrapper(R (L::*)(Args...) const)
  23. -> LambdaWrapper<L, R, Args...>; // undefined!
  24.  
  25. template <typename L>
  26. auto lambda_to_wrapper(const L&)
  27. -> decltype(mem_func_to_wrapper(&L::operator())); // undefined!
  28.  
  29. int main() {
  30. std::size_t toBeCaptured = 100;
  31. auto lambda =
  32. [&](std::string& str) -> std::size_t {
  33. return toBeCaptured + str.length();
  34. };
  35. typedef decltype(lambda_to_wrapper(lambda)) CallbackSupportType;
  36. CallbackSupportType::set(lambda);
  37. std::size_t (*pFunc)(std::string&) = &CallbackSupportType::callback;
  38. std::string str("may work?");
  39. std::size_t ret = pFunc(str);
  40. std::cout << "Result: " << ret << std::endl;
  41. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
Result: 109