code_junkie

C++ metaprogramming - generating errors in code

Nov 13th, 2011
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. template <int number1>
  2. void reportErrorIfLessThan10()
  3. {
  4. #if(number1 < 10)
  5. #error the number is less than 10
  6. #endif
  7. }
  8.  
  9.  
  10. int maint(int argc, char**argv)
  11. {
  12. reportErrorIfLessThan10<5>();//report an error!
  13. reportErrorIfLessThan10<12>();//ok
  14. return 0;
  15. }
  16.  
  17. template<bool> class static_check
  18. {
  19. };
  20.  
  21. template<> class static_check<false>
  22. {
  23. private: static_check();
  24. };
  25.  
  26. #define StaticAssert(test) static_check<(test) != 0>()
  27.  
  28. template <int number1>
  29. void reportErrorIfLessThan10()
  30. {
  31. typedef char number1_gt_10[number1 > 10 ? 1 : -1];
  32. }
  33.  
  34.  
  35. int maint(int argc, char**argv)
  36. {
  37. reportErrorIfLessThan10<5>();//report an error!
  38. reportErrorIfLessThan10<12>();//ok
  39. return 0;
  40. }
  41.  
  42. #define static_assert(test, message) typedef char static_assert_at_ ## __LINE__[(test) ? 1 : -1];
  43.  
  44. template <int number1>
  45. typename boost::enable_if_c< (number1 >= 10) >::type
  46. reportErrorIfLessThan10() {
  47. // ...
  48. }
  49.  
  50. template<bool C, typename T = void>
  51. struct enable_if {
  52. typedef T type;
  53. };
  54.  
  55. template<typename T>
  56. struct enable_if<false, T> { };
  57.  
  58. template <int number1>
  59. void reportErrorIfLessThan10() {
  60. static_assert(number >= 10, "number must be >= 10");
  61. }
  62.  
  63. template <int number1>
  64. void reportErrorIfLessThan10() {
  65. BOOST_STATIC_ASSERT(number >= 10);
  66. }
  67.  
  68. namespace detail {
  69. /* chooses type A if cond == true, chooses type B if cond == false */
  70. template <bool cond, typename A, typename B>
  71. struct Condition {
  72. typedef A type;
  73. };
  74.  
  75. template <typename A, typename B>
  76. struct Condition<false, A, B> {
  77. typedef B type;
  78. };
  79.  
  80. struct number1_greater_than_10;
  81. }
  82.  
  83. template <int number1>
  84. void reportErrorIfLessThan10() {
  85. // number1 must be greater than 10
  86. sizeof( typename detail::Condition< (number1 >= 10),
  87. char,
  88. detail::number1_greater_than_10
  89. >::type );
  90. }
  91.  
  92. template <int N>
  93. struct helper : helper<N - 1> { };
  94.  
  95. template <>
  96. struct helper<10> { typedef void type; };
  97.  
  98. template <>
  99. struct helper<0> { }; // Notice: missing typedef.
  100.  
  101. template <int N>
  102. typename helper<N>::type error_if_less_than_10() {
  103. }
  104.  
  105. int main() {
  106. error_if_less_than_10<10>();
  107. error_if_less_than_10<9>();
  108. }
  109.  
  110. x.cpp:16: error: no matching function for call to 'error_if_less_than_10()'
Add Comment
Please, Sign In to add comment