make_unique.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. (c) 2014-2015 Glen Joseph Fernandes
  3. <glenjofe -at- gmail.com>
  4. Distributed under the Boost Software
  5. License, Version 1.0.
  6. http://boost.org/LICENSE_1_0.txt
  7. */
  8. #ifndef BOOST_SMART_PTR_MAKE_UNIQUE_HPP
  9. #define BOOST_SMART_PTR_MAKE_UNIQUE_HPP
  10. #include <boost/config.hpp>
  11. #include <memory>
  12. #include <utility>
  13. namespace boost {
  14. namespace detail {
  15. template<class T>
  16. struct up_if_object {
  17. typedef std::unique_ptr<T> type;
  18. };
  19. template<class T>
  20. struct up_if_object<T[]> { };
  21. template<class T, std::size_t N>
  22. struct up_if_object<T[N]> { };
  23. template<class T>
  24. struct up_if_array { };
  25. template<class T>
  26. struct up_if_array<T[]> {
  27. typedef std::unique_ptr<T[]> type;
  28. };
  29. template<class T>
  30. struct up_remove_reference {
  31. typedef T type;
  32. };
  33. template<class T>
  34. struct up_remove_reference<T&> {
  35. typedef T type;
  36. };
  37. template<class T>
  38. struct up_remove_reference<T&&> {
  39. typedef T type;
  40. };
  41. template<class T>
  42. struct up_element { };
  43. template<class T>
  44. struct up_element<T[]> {
  45. typedef T type;
  46. };
  47. } /* detail */
  48. template<class T>
  49. inline typename detail::up_if_object<T>::type make_unique()
  50. {
  51. return std::unique_ptr<T>(new T());
  52. }
  53. #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
  54. template<class T, class... Args>
  55. inline typename detail::up_if_object<T>::type
  56. make_unique(Args&&... args)
  57. {
  58. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  59. }
  60. #endif
  61. template<class T>
  62. inline typename detail::up_if_object<T>::type
  63. make_unique(typename detail::up_remove_reference<T>::type&& value)
  64. {
  65. return std::unique_ptr<T>(new T(std::move(value)));
  66. }
  67. template<class T>
  68. inline typename detail::up_if_object<T>::type make_unique_noinit()
  69. {
  70. return std::unique_ptr<T>(new T);
  71. }
  72. template<class T>
  73. inline typename detail::up_if_array<T>::type make_unique(std::size_t n)
  74. {
  75. return std::unique_ptr<T>(new
  76. typename detail::up_element<T>::type[n]());
  77. }
  78. template<class T>
  79. inline typename detail::up_if_array<T>::type
  80. make_unique_noinit(std::size_t n)
  81. {
  82. return std::unique_ptr<T>(new
  83. typename detail::up_element<T>::type[n]);
  84. }
  85. } /* boost */
  86. #endif