2013-07-27 18 views

Odpowiedz

20

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.

36

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

+0

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? –

+2

@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 ()', dopasuje on wersję '_Known_bound' i spowoduje błąd. – Praetorian

+2

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++? –

Powiązane problemy