Mój kompilator nie obsługuje make_unique. Jak napisać?Jak zaimplementować funkcję make_unique w C++ 11?
template< class T, class... Args > unique_ptr<T> make_unique(Args&&... args);
Mój kompilator nie obsługuje make_unique. Jak napisać?Jak zaimplementować funkcję make_unique w C++ 11?
template< class T, class... Args > unique_ptr<T> make_unique(Args&&... args);
Skopiowano z make_unique and perfect forwarding (to samo podano w Herb Sutter's blog)
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Jeśli jest to potrzebne w VC2012, zobacz Is there a way to write make_unique() in VS2012?
Niemniej jednak, jeśli roztwór w sasha.sochka's answer kompiluje się z kompilatora, chciałbym iść z tamtym. Jest to bardziej rozbudowane i działa również z tablicami.
Wersja Stephan T. Lavavej (znany również przez STL), który pierwotnie proponowanej dodanie tej funkcji w C++ 14
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
namespace std {
template<class T> struct _Unique_if {
typedef unique_ptr<T> _Single_object;
};
template<class T> struct _Unique_if<T[]> {
typedef unique_ptr<T[]> _Unknown_bound;
};
template<class T, size_t N> struct _Unique_if<T[N]> {
typedef void _Known_bound;
};
template<class T, class... Args>
typename _Unique_if<T>::_Single_object
make_unique(Args&&... args) {
return unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<class T>
typename _Unique_if<T>::_Unknown_bound
make_unique(size_t n) {
typedef typename remove_extent<T>::type U;
return unique_ptr<T>(new U[n]());
}
template<class T, class... Args>
typename _Unique_if<T>::_Known_bound
make_unique(Args&&...) = delete;
}
EDIT: uaktualniony kod do standardowej N3656 rewizji
W jaki sposób struktura '_Known_bound' pasuje, gdy nie używa się' _Unique_if 'określa drugi argument szablonu i nie ma wartości domyślnej? –
@BenJackson Celem jest, aby nigdy nie było dopasowania dla wersji '_Known_bound', gdy' make_unique' jest używane poprawnie. Jeśli ktoś spróbuje użyć go jako 'make_unique
Jaki jest dobry sposób dołączenia tej definicji do kodu C++, który może zostać skompilowany w środowisku, w którym make_unique jest dostępny w stdC++? –
możliwy duplikat [Czy istnieje sposób napisania make_unique() w VS2012?] (Http://stackoverflow.com/q/12547983/341970) – Ali