Is there a way to write make_unique() in VS2012?

前端 未结 6 1353
情书的邮戳
情书的邮戳 2020-12-03 07:44

Herb Sutter propose a simple implementation of make_unique() there: http://herbsutter.com/gotw/_102/

Here it is:

template

        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 08:31

    I have extended Hugues's answer to handle creating unique pointers which wrap arrays (basically merged it with the code in this paper) and obtained the following, which works fine in my VC2012 projects:

    #include 
    
    template struct _Unique_if {
        typedef std::unique_ptr _Single_object;
    };
    
    template struct _Unique_if {
        typedef std::unique_ptr _Unknown_bound;
    };
    
    template struct _Unique_if {
        typedef void _Known_bound;
    };
    
    // Visual Studio 2012 - specific
    #define _MAKE_UNIQUE(TEMPLATE_LIST, PADDING_LIST, LIST, COMMA, X1, X2, X3, X4)                                          \
    template inline typename _Unique_if::_Single_object make_unique(LIST(_TYPE_REFREF_ARG))  \
    {                                                                                                                            \
        return std::unique_ptr(new T(LIST(_FORWARD_ARG)));                                                                    \
    }
    _VARIADIC_EXPAND_0X(_MAKE_UNIQUE, , , , )
    #undef _MAKE_UNIQUE
    
    template inline typename _Unique_if::_Unknown_bound make_unique(size_t n) 
    {
        typedef typename std::remove_extent::type U;
        return std::unique_ptr(new U[n]());
    }
    
    // Visual Studio 2012 - specific
    #define _MAKE_UNIQUE(TEMPLATE_LIST, PADDING_LIST, LIST, COMMA, X1, X2, X3, X4)                                          \
    template typename _Unique_if::_Known_bound make_unique(LIST(_TYPE_REFREF_ARG)) = delete;
    _VARIADIC_EXPAND_0X(_MAKE_UNIQUE, , , , )
    #undef _MAKE_UNIQUE
    

提交回复
热议问题