Herb Sutter propose a simple implementation of make_unique()
there: http://herbsutter.com/gotw/_102/
Here it is:
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
My problem is that variadic templates are not yet part of VS2012, so I can't use this code as is.
Is there a maintainable way to write this in VS2012 that wouldn't involve copy-pasting the same function with different args count?
Even though variadic templates are not part of VS2012, there are macros built into the header file
<memory>
that help simulate them.See this very nice answer which shows how to implement
make_unique<T>
in just a few cryptic lines. I confirmed that it works well:I know I am late to the party here, but I just came across this. I have been doing this with a one-liner macro (and is VS2012 compatible):
Or less portable, but you can pass in empty params
Use like this:
You could use Boost.Preprocessor to generate the different parameter counts, but I really don't see the advantage of that. Simply do the grunt job once, stuff it in a header and be done. You're saving yourself compile time and have your
make_unique
.Here's a copy-paste of my
make_unique.h
header that simulates variadic templates for up to 5 arguments.Since OP seems to not like copy-paste work, here's the Boost.Preprocessor code to generate the above:
First, make a main header that includes the template header multiple times (Boost.Preprocessor iteration code blatantly stolen from this answer):
And now make a template header that gets included again and again and expands differently depending on the value of
MAKE_UNIQUE_NUM_ARGS
:Just out of curiosity I have tried to make similar thing - I needed to support more arguments than 4 - for _VARIADIC_EXPAND_0X kind of solution - probably only 4 will be supported.
Here is MacroArg.h header file:
Some of details on debugging macros can be found here (similar kind of problem being discussed)
How can I add reflection to a C++ application?
I have extended Hugues's answer to handle creating unique pointers which wrap arrays (basically merged it with the code in this paper) and obtained the following, which works fine in my VC2012 projects:
The only way to simulate functions with variadic argument lists is by creating a suitable list of overloads. Whether this is done manually, using something like the Boost preprocessor library, or using a suitable generator all amounts to the same: real variadic argument lists cannot be simulated. Personally, I think the most maintainable version of simulating variadic argument lists is to use a compiler which supports them as preprocessor and have it generate code suitable to be compiled by compilers not, yet, up to support variadic templates.