I'm trying to create and use make_unique
for std::unique_ptr
, in the same way std::make_shared
exists for std::shared_ptr
described here. Herb Sutter mentions the possible implementation of make_unique
that looks like this:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
It doesn't seem to work for me. I'm using the following sample program:
// 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
}
And the compiler (I'm using VS2010) gives me the following output:
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?)
Also if you replace the make_unique
implementation to the following
template<class T, class U>
std::unique_ptr<T> make_unique(U&& u) {
return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
(which is taken from this example), it compiles and works fine.
Can anyone tell me what's the problem? It seems to me that VS2010 is having some trouble with ...
in template declaration, and I don't know what can I do about it.