9

make_uniqueforを作成して使用しようとしていますが、ここで説明されているstd::unique_ptrforと同じように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...のテンプレート宣言で問題が発生しているように思えますが、どうすればよいかわかりません。

4

2 に答える 2

14

可変個引数テンプレートは、リリースされたバージョンのVisual C ++ 11では使用できません。ただし、さまざまな数のパラメーターに対して大量のコピー/貼り付けコードを使用して引数の展開をシミュレートするか、Microsoft独自の実装で使用されているのと同じコンパイラートリックを使用できます。 「疑似可変個引数」。ハーブサッターのブログのこのコメントから: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
于 2012-12-14T18:03:05.900 に答える
5

MSDNによると、可変個引数テンプレートはVisual C++2010または2012ではサポートされていません。

于 2012-12-14T17:55:04.123 に答える