Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing constructor parameters to a template function factory

Tags:

c++

templates

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 templates 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)

like image 818
UnTraDe Avatar asked Dec 09 '25 23:12

UnTraDe


1 Answers

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 function template:

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

You will have a unary function template:

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 function template:

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 function template:

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<>().

like image 86
Andy Prowl Avatar answered Dec 12 '25 11:12

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!