fork(1) download
  1. #include <iostream>
  2.  
  3. /* strlen as constant expression */
  4. constexpr int my_strlen(const char *s)
  5. {
  6. const char *p = s;
  7. while ('\0' != *p) ++p;
  8. return p-s;
  9. }
  10.  
  11. /* Degree to radian conversion as constant expression */
  12. constexpr const float pi = 3.14f; // const is not enough!
  13.  
  14. constexpr float degree2radian(float degree)
  15. {
  16. return degree * pi / 180.0f;
  17. }
  18.  
  19. /* Power function as constant expression */
  20. // C++11
  21. constexpr int my_pow(int base, int exp)
  22. {
  23. return exp == 0 ? 1 : base * my_pow(base, exp-1);
  24. }
  25.  
  26. // C++14
  27. /*constexpr int my_pow(int base, int exp)
  28. {
  29.   auto result = 1;
  30.   for (int i = 0; i < exp; ++i)
  31.   result *= base;
  32.   return result;
  33. }*/
  34.  
  35. // Output function that requires a compile-time constant, for testing
  36. template<int n> struct constN
  37. {
  38. constN() { std::cout << n << std::endl; }
  39. };
  40.  
  41. int main()
  42. {
  43. // C++11:
  44. // prog.cpp: In function 'constexpr int my_strlen(const char*)':
  45. // prog.cpp:9:1: error: body of constexpr function 'constexpr int my_strlen(const char*)' not a return-statement
  46. std::cout << "String length: " << my_strlen("Hello World!") << std::endl;
  47.  
  48. std::cout << degree2radian(60.0f) << std::endl;
  49.  
  50. int b = 4; // could be user input
  51. std::cout << "2^10 = "; constN<my_pow(2, 10)> out1; // guaranteed to be evaluated in compile time
  52. std::cout << "3^10 = " << my_pow(3, 10) << std::endl; // can be evaluated in compile time
  53. std::cout << b << "^10 = " << my_pow(b, 10) << std::endl; // computed at runtime
  54.  
  55. // prog.cpp:32:51: error: the value of 'b' is not usable in a constant expression
  56. // test.cpp:25:7: note: 'int b' is not const
  57. std::cout << b << "^10 = "; constN<my_pow(b, 10)> out2;
  58. return 0;
  59. }
  60.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:57:50: error: the value of 'b' is not usable in a constant expression
   std::cout << b << "^10 = "; constN<my_pow(b, 10)> out2; 
                                                  ^
prog.cpp:50:7: note: 'int b' is not const
   int b = 4;                                                // could be user input
       ^
prog.cpp:57:51: error: the value of 'b' is not usable in a constant expression
   std::cout << b << "^10 = "; constN<my_pow(b, 10)> out2; 
                                                   ^
prog.cpp:50:7: note: 'int b' is not const
   int b = 4;                                                // could be user input
       ^
prog.cpp:57:51: note: in template argument for type 'int' 
   std::cout << b << "^10 = "; constN<my_pow(b, 10)> out2; 
                                                   ^
stdout
Standard output is empty