Here is another solution (in addition to Mike's):
#include <type_traits>
#include <utility>
#include <memory>
template <class T, class ...Args>
typename std::enable_if
<
!std::is_array<T>::value,
std::unique_ptr<T>
>::type
make_unique(Args&& ...args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <class T>
typename std::enable_if
<
std::is_array<T>::value,
std::unique_ptr<T>
>::type
make_unique(std::size_t n)
{
typedef typename std::remove_extent<T>::type RT;
return std::unique_ptr<T>(new RT[n]);
}
int main()
{
auto p1 = make_unique<int>(3);
auto p2 = make_unique<int[]>(3);
}
Notes:
- new T[n] should just default construct n T's.
So make_unique(n) should just default construct n T's.
- Issues like this contributed to make_unique not being proposed in C++11. Another issue is: Do we handle custom deleters?
These are not unanswerable questions. But they are questions that haven't yet been fully answered.