enable_if_test.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright 2018 Glen Joseph Fernandes
  3. (glenjofe@gmail.com)
  4. Distributed under the Boost Software License,
  5. Version 1.0. (See accompanying file LICENSE_1_0.txt
  6. or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #include <boost/type_traits/enable_if.hpp>
  9. #include "test.hpp"
  10. template<bool B>
  11. struct Constant {
  12. enum {
  13. value = B
  14. };
  15. };
  16. template<class T>
  17. struct Check
  18. : Constant<false> { };
  19. template<>
  20. struct Check<long>
  21. : Constant<true> { };
  22. class Construct {
  23. public:
  24. template<class T>
  25. Construct(T, typename boost::enable_if_<Check<T>::value>::type* = 0)
  26. : value_(true) { }
  27. template<class T>
  28. Construct(T, typename boost::enable_if_<!Check<T>::value>::type* = 0)
  29. : value_(false) { }
  30. bool value() const {
  31. return value_;
  32. }
  33. private:
  34. bool value_;
  35. };
  36. template<class T, class E = void>
  37. struct Specialize;
  38. template<class T>
  39. struct Specialize<T, typename boost::enable_if_<Check<T>::value>::type>
  40. : Constant<true> { };
  41. template<class T>
  42. struct Specialize<T, typename boost::enable_if_<!Check<T>::value>::type>
  43. : Constant<false> { };
  44. template<class T>
  45. typename boost::enable_if_<Check<T>::value, bool>::type Returns(T)
  46. {
  47. return true;
  48. }
  49. template<class T>
  50. typename boost::enable_if_<!Check<T>::value, bool>::type Returns(T)
  51. {
  52. return false;
  53. }
  54. #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
  55. template<class T>
  56. boost::enable_if_t<Check<T>::value, bool> Alias(T)
  57. {
  58. return true;
  59. }
  60. template<class T>
  61. boost::enable_if_t<!Check<T>::value, bool> Alias(T)
  62. {
  63. return false;
  64. }
  65. #endif
  66. TT_TEST_BEGIN(enable_if)
  67. BOOST_CHECK(!Construct(1).value());
  68. BOOST_CHECK(Construct(1L).value());
  69. BOOST_CHECK(!Specialize<int>::value);
  70. BOOST_CHECK(Specialize<long>::value);
  71. BOOST_CHECK(!Returns(1));
  72. BOOST_CHECK(Returns(1L));
  73. #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
  74. BOOST_CHECK(!Alias(1));
  75. BOOST_CHECK(Alias(1L));
  76. #endif
  77. TT_TEST_END