fork(1) download
  1. #include <iostream>
  2.  
  3. void do_something_with(int N) { std::cout << "2 + 3 = " << N << std::endl; }
  4.  
  5. template <int N>
  6. using int_c = std::integral_constant<int, N>;
  7.  
  8. // Compile time
  9. template <int N> void f(int_c<N>) = delete;
  10. void f(int_c<5>N) { do_something_with(N); }
  11.  
  12. // Runtime
  13. void f(int N){
  14. if (N != 5){
  15. std::abort();
  16. }
  17. f(int_c<5>{});
  18. }
  19.  
  20. template <std::size_t N>
  21. constexpr int to_number(const int (&a)[N])
  22. {
  23. int res = 0;
  24. for (auto e : a) {
  25. res *= 10;
  26. res += e;
  27. }
  28. return res;
  29. }
  30.  
  31. template <char ... Ns>
  32. constexpr int_c<to_number({(Ns - '0')...})> operator ""_c ()
  33. {
  34. return {};
  35. }
  36.  
  37. int main(){
  38. f(5_c); // ok
  39. // f(6_c); // error: use of deleted function ‘void f(int_c<N>) [with int N = 6; int_c<N> = std::integral_constant<int, 6>]’
  40. f(5); // ok
  41. std::cout << "it will abort" << std::endl;
  42. f(6); // abort at runtime
  43. std::cout << "never reach" << std::endl;
  44. }
Runtime error #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
2 + 3 = 5
2 + 3 = 5
it will abort