2

Given a template class:

template<class T>
class Foo
{
public:
    void FunctionThatCreatesT()
    {
        _object = new T;
    }
private:
    shared_ptr<T> _object;
}

Is it possible to somehow pass a set of constructor parameters for T to Foo (perhaps when Foo is constructed) such that Foo can use them when it creates T? A C++11 only solution is fine (so, variadics are on the table for example).

dicroce
  • 45,396
  • 28
  • 101
  • 140

1 Answers1

3

Exactly that, variadic templates and perfect forwarding via std::forward.

#include <memory>
#include <utility>

template<class T>
class Foo
{
public:
    template<class... Args>
    void FunctionThatCreatesT(Args&&... args)
    {
        _object = new T(std::forward<Args>(args)...);
    }
private:
    std::shared_ptr<T> _object;
}

For a listing of how this works, see this excellent answer.

You can emulate a limited version of this in C++03 with many overloaded functions, but.. it's a PITA.

Also, this is only from memory, so no testing done. Might contain an off-by-one error.

Community
  • 1
  • 1
Xeo
  • 129,499
  • 52
  • 291
  • 397