【发布时间】:2012-12-02 18:11:50
【问题描述】:
我正在尝试为std::unique_ptr 创建和使用make_unique,就像std::make_shared 存在于std::shared_ptr described here 一样。 Herb Sutter mentions 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)... ) );
}
这似乎对我不起作用。我正在使用以下示例程序:
// 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
}
编译器(我使用的是 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?)
另外,如果您将 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)));
}
(取自this 示例),它可以编译并正常工作。
谁能告诉我有什么问题?在我看来,VS2010 在模板声明中 ... 出现了一些问题,我不知道该怎么办。
【问题讨论】:
-
自 CTP 起才支持可变参数模板。
-
您应该注意 Herb Sutter 的建议不适用于数组类型。 Stephan T Lavavej 在他最近一集中的 Core C++ 中发布了一个改进版本,它也适用于数组,例如
make_unique<int[]>(1, 2, 3)。 -
如果您想在 Visual Studio 中使用可变参数模板,您需要最新的更新。我自己的指示:scrupulousabstractions.tumblr.com/post/36204698243/…
-
您的 make_unique 示例无法为我编译。我得到
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
标签: c++ visual-studio-2010 visual-c++ c++11 variadic-templates