UnTraDe UnTraDe - 1 month ago 8
C++ Question

Passing constructor parameters to a template function factory

I have this function:

template <class T>
T *allocate()
{
T *obj = new(top) T();
top += sizeof(T);
return obj;
}


Now, it's working great creating objects with default constructors but how do I create objects who need to be passed new parameters?

I know it can be achieved using C++11's variadic
template
s but how can I do this without C++11 functionality? (Apparently my version of VS2012 don't support this feature yet, but I would like to know how to do this without this feature even if an upgrade will fix it)

Answer

There isn't a language feature that replaces variadic templates (of course, otherwise they wouldn't have been invented).

You can provide several overloads that accept up to N parameters (for a reasonable choice of N). Each overload would perfect-forward its argument to the constructor of T.

So apart from your nullary template function:

template <class T>
T *allocate()
{
    T *obj = new(top) T();
    top += sizeof(T);
    return obj;
}

You will have a unary template function:

template <class T, class P1>
T *allocate(P1&& p1)
{
    T *obj = new(top) T(std::forward<P1>(p1));
    top += sizeof(T);
    return obj;
}

A binary template function:

template <class T, class P1, class P2>
T *allocate(P1&& p1, P2&& p2)
{
    T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2));
    top += sizeof(T);
    return obj;
}

A ternary template function:

template <class T, class P1, class P2, class P3>
T *allocate(P1&& p1, P2&& p2, P3&& p3)
{
    T *obj = new(top) T(std::forward<P1>(p1), std::forward<P2>(p2), 
                        std::forward<P3>(p3));
    top += sizeof(T);
    return obj;
}

And so on (you get the point). If you mind the code replication, you can figure out some macros that would reduce the pain - but they do not eliminate it, especially if you are not fond of macros.

Don't forget to:

#include <utility>

To have access to std::forward<>().

Comments