integral-branching.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright Louis Dionne 2013-2017
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  4. #include <boost/hana.hpp>
  5. #include <boost/hana/ext/std/integral_constant.hpp>
  6. #include <memory>
  7. #include <string>
  8. #include <type_traits>
  9. #include <utility>
  10. namespace hana = boost::hana;
  11. namespace ns1 {
  12. //! [make_unique.if_]
  13. template <typename T, typename ...Args>
  14. std::unique_ptr<T> make_unique(Args&&... args) {
  15. return hana::if_(std::is_constructible<T, Args...>{},
  16. [](auto&& ...x) { return std::unique_ptr<T>(new T(std::forward<Args>(x)...)); },
  17. [](auto&& ...x) { return std::unique_ptr<T>(new T{std::forward<Args>(x)...}); }
  18. )(std::forward<Args>(args)...);
  19. }
  20. //! [make_unique.if_]
  21. }
  22. namespace ns2 {
  23. //! [make_unique.eval_if]
  24. template <typename T, typename ...Args>
  25. std::unique_ptr<T> make_unique(Args&&... args) {
  26. return hana::eval_if(std::is_constructible<T, Args...>{},
  27. [&](auto _) { return std::unique_ptr<T>(new T(std::forward<Args>(_(args))...)); },
  28. [&](auto _) { return std::unique_ptr<T>(new T{std::forward<Args>(_(args))...}); }
  29. );
  30. }
  31. //! [make_unique.eval_if]
  32. }
  33. struct Student {
  34. std::string name;
  35. int age;
  36. };
  37. int main() {
  38. {
  39. std::unique_ptr<int> a = ns1::make_unique<int>(3);
  40. std::unique_ptr<Student> b = ns1::make_unique<Student>("Bob", 25);
  41. }
  42. {
  43. std::unique_ptr<int> a = ns2::make_unique<int>(3);
  44. std::unique_ptr<Student> b = ns2::make_unique<Student>("Bob", 25);
  45. }
  46. }