make_unique
forを作成して使用しようとしていますが、ここで説明されているstd::unique_ptr
forと同じようにstd::make_shared
存在します。Herb Sutterは、次のような実装の可能性について言及しています。std::shared_ptr
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)));
}
(これはこの例から取得したものです)、コンパイルして正常に動作します。
誰が私に何が問題なのか教えてもらえますか? VS2010...
のテンプレート宣言で問題が発生しているように思えますが、どうすればよいかわかりません。