make_unique不编译

Saa*_*age 9 c++ visual-studio-2010 visual-c++ variadic-templates c++11

我试图创建和使用make_uniquestd::unique_ptr,以同样的方式std::make_shared对存在std::shared_ptr 这里描述.Herb Sutter 提到了可能的实现make_unique,如下所示:

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
Run Code Online (Sandbox Code Playgroud)

它似乎对我不起作用.我正在使用以下示例程序:

// testproject.cpp : Defines the entry point for the console application.
#include "stdafx.h"

#include <iostream>
#include <memory>
#include <utility>

struct A {
  A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
  A(int& n)  { std::cout << "lvalue overload, n=" << n << "\n"; }
};

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args ) {
  return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

int main() {
  std::unique_ptr<A> p1 = make_unique<A>(2); // rvalue
  int i = 1;
  std::unique_ptr<A> p2 = make_unique<A>(i); // lvalue
}
Run Code Online (Sandbox Code Playgroud)

编译器(我正在使用VS2010)给我以下输出:

1>d:\projects\testproject\testproject\testproject.cpp(15): error C2143: syntax error : missing ',' before '...'
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2065: 'Args' : undeclared identifier
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2988: unrecognizable template declaration/definition
1>d:\projects\testproject\testproject\testproject.cpp(16): error C2059: syntax error : '...'
1>d:\projects\testproject\testproject\testproject.cpp(22): error C2143: syntax error : missing ';' before '{'
1>d:\projects\testproject\testproject\testproject.cpp(22): error C2447: '{' : missing function header (old-style formal list?)
Run Code Online (Sandbox Code Playgroud)

此外,如果您将make_unique实现替换为以下

template<class T, class U>
std::unique_ptr<T> make_unique(U&& u) {
  return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
Run Code Online (Sandbox Code Playgroud)

(取自这个例子),它编译并正常工作.

谁能告诉我这是什么问题?在我看来,VS2010 ...在模板声明方面遇到了一些麻烦,我不知道我能做些什么.

Bre*_*hns 14

Visual C++ 11的发布版本中没有可用的变量模板.但是,您可以使用大量复制/粘贴代码模拟不同数量参数的参数扩展,或者使用Microsoft自己实现的相同编译器技巧. "伪variadics".来自Herb Sutter博客的评论:http://herbsutter.com/gotw/_102/#comment-6428

#include <memory> // brings in TEMPLATE macros.

#define _MAKE_UNIQUE(TEMPLATE_LIST, PADDING_LIST, LIST, COMMA, X1, X2, X3, X4)  \
\
template<class T COMMA LIST(_CLASS_TYPE)>    \
inline std::unique_ptr<T> make_unique(LIST(_TYPE_REFREF_ARG))    \
{    \
    return std::unique_ptr<T>(new T(LIST(_FORWARD_ARG)));    \
}

_VARIADIC_EXPAND_0X(_MAKE_UNIQUE, , , , )
#undef _MAKE_UNIQUE
Run Code Online (Sandbox Code Playgroud)

  • 注意:使用`_ [AZ].*`标识符保留给实现(在您的情况下,VC++编译器和Dirkumware STL). (3认同)

Mik*_*our 5

根据MSDN,Visual C++ 2010或2012不支持可变参数模板.

  • [VC++ 2012年11月CTP可以在这里找到](http://www.microsoft.com/en-us/download/details.aspx?id=35515) (2认同)