Brian Silverman | f819b44 | 2019-01-20 16:51:04 -0800 | [diff] [blame^] | 1 | #ifndef AOS_MAKE_UNIQUE_H_ |
| 2 | #define AOS_MAKE_UNIQUE_H_ |
| 3 | |
| 4 | // TODO(brian): Replace this file with ::std::make_unique once all our |
| 5 | // toolchains have support. |
| 6 | |
| 7 | namespace aos { |
| 8 | |
| 9 | /// Constructs a `new T()` with the given args and returns a |
| 10 | /// `unique_ptr<T>` which owns the object. |
| 11 | /// |
| 12 | /// Example: |
| 13 | /// |
| 14 | /// auto p = make_unique<int>(); |
| 15 | /// auto p = make_unique<std::tuple<int, int>>(0, 1); |
| 16 | template <class T, class... Args> |
| 17 | typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type |
| 18 | make_unique(Args &&... args) { |
| 19 | return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); |
| 20 | } |
| 21 | |
| 22 | /// Constructs a `new T[n]` with the given args and returns a |
| 23 | /// `unique_ptr<T[]>` which owns the object. |
| 24 | /// |
| 25 | /// \param n size of the new array. |
| 26 | /// |
| 27 | /// Example: |
| 28 | /// |
| 29 | /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's. |
| 30 | template <class T> |
| 31 | typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, |
| 32 | std::unique_ptr<T>>::type |
| 33 | make_unique(size_t n) { |
| 34 | return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]()); |
| 35 | } |
| 36 | |
| 37 | /// This function isn't used and is only here to provide better compile errors. |
| 38 | template <class T, class... Args> |
| 39 | typename std::enable_if<std::extent<T>::value != 0>::type |
| 40 | make_unique(Args &&...) = delete; |
| 41 | |
| 42 | } // namespace aos |
| 43 | |
| 44 | #endif // AOS_MAKE_UNIQUE_H_ |