fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <string>
  4. #include <type_traits>
  5.  
  6. template<typename T, typename F=typename std::function<T()>>
  7. class lazy {
  8. //TYPES
  9. using uninit_t=typename std::aligned_storage<
  10. sizeof(T),
  11. std::alignment_of<T>::value
  12. >::type;
  13. //MEMBERS
  14. F f;
  15. uninit_t value;
  16. bool cached { false };
  17. public:
  18. lazy(F f_) : f { f_ }{ }
  19.  
  20. T& get() {
  21. if(!cached) {
  22. new(&value) T(f());
  23. cached=true;
  24. }
  25. return reinterpret_cast<T&>(value);
  26. }
  27. ~lazy() {
  28. if(cached)
  29. get().~T();
  30. }
  31. };
  32.  
  33.  
  34. std::string make_big_string() {
  35. std::cerr << "making string\n";
  36. return "hello, world";
  37. }
  38.  
  39. template<typename F>
  40. lazy<
  41. typename std::remove_reference<
  42. typename std::result_of<F()>::type
  43. >::type,
  44. F
  45. > make_lazy(F f) { return { f }; }
  46.  
  47. int main() {
  48. auto l_str=make_lazy(make_big_string);
  49.  
  50.  
  51. std::cout << "get2\t" << l_str.get() << '\n';
  52. std::cout << "get2\t" << l_str.get() << '\n';
  53. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:9:11: error: expected nested-name-specifier before 'uninit_t'
prog.cpp:9:11: error: using-declaration for non-member at class scope
prog.cpp:9:19: error: expected ';' before '=' token
prog.cpp:9:19: error: expected unqualified-id before '=' token
prog.cpp:15:5: error: 'uninit_t' does not name a type
prog.cpp:16:10: error: function definition does not declare parameters
prog.cpp: In member function 'T& lazy<T, F>::get()':
prog.cpp:21:13: error: 'cached' was not declared in this scope
prog.cpp:22:18: error: 'value' was not declared in this scope
prog.cpp:25:37: error: 'value' was not declared in this scope
prog.cpp: In destructor 'lazy<T, F>::~lazy()':
prog.cpp:28:12: error: 'cached' was not declared in this scope
stdout
Standard output is empty