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