fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. #if 1
  7. #ifdef _MSC_VER
  8. #define NO_INLINE __declspec(noinline)
  9. #else
  10. #define NO_INLINE __attribute__((noinline))
  11. #endif
  12. #else
  13. #define NO_INLINE
  14. #endif
  15.  
  16. void use(void *p)
  17. {
  18. static auto volatile t=p;
  19. };
  20.  
  21. template<typename T,unsigned N,typename F>
  22. NO_INLINE auto cps_alloca_static(F &&f) -> decltype(f(nullptr))
  23. {
  24. T data[N];
  25. return f(&data[0]);
  26. }
  27.  
  28. template<typename T,typename F>
  29. NO_INLINE auto cps_alloca_dynamic(unsigned n,F &&f) -> decltype(f(nullptr))
  30. {
  31. vector<T> data(n);
  32. return f(&data[0]);
  33. }
  34.  
  35. template<typename T,typename F>
  36. auto cps_alloca(unsigned n,F &&f) -> decltype(f(nullptr))
  37. {
  38. switch(n)
  39. {
  40. case 1: return cps_alloca_static<T,1>(f);
  41. case 2: return cps_alloca_static<T,2>(f);
  42. case 3: return cps_alloca_static<T,3>(f);
  43. case 4: return cps_alloca_static<T,4>(f);
  44. default: return cps_alloca_dynamic<T>(n,f);
  45. }; // mpl::for_each / array / index pack / recursive bsearch / etc variaciĆ³n
  46. }
  47.  
  48. struct Payload
  49. {
  50. volatile char d[2048];
  51. };
  52.  
  53. void test(unsigned n)
  54. {
  55. volatile char begin;
  56. cps_alloca<Payload>(n,[&](Payload *p)
  57. {
  58. volatile char end;
  59. const auto overhead = &begin-&end - int(n*sizeof(Payload));
  60. cout << "n=" << n << "\toverhead=" << overhead << endl;
  61. use(p);
  62. });
  63. }
  64.  
  65. int main()
  66. {
  67. for(auto i=1u;i!=6u;++i)
  68. test(i);
  69. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
n=1	overhead=24
n=2	overhead=24
n=3	overhead=24
n=4	overhead=24
n=5	overhead=-10200