This page looks best with JavaScript enabled

Implement std::make_unique in C++11

 ·  ☕ 1 min read · 👀... views

Problem description

If your project was using standard C++11 and you wanted to copy an open source file somewhere which contains the use of std::make_unique function, you might get compile error

error: ‘make_unique’ is not a member of ‘std’

Because std::make_unique was added in C++14, not available in C++11.

Solution

Add a wrapper template in a common header file in your project:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespace details {
// make_unique support for pre c++14

#if __cplusplus >= 201402L // C++14 and beyond
using std::make_unique;
#else
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&... args)
{
    static_assert(!std::is_array<T>::value, "arrays not supported");
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif
} // namespace details

Then, convert the origin usage of std::make_unique to details::make_unique. For instance:

1
2
3
4
Boundary::Ptr Boundary::create()
{
    return std::make_unique<BoundaryImpl>("bundle", 0, true);
}

References

Share on