Home > Software design >  Value initialization of template object using new
Value initialization of template object using new

Time:08-14

I have a class with a pointer to T

template <typename T>
class ScopedPtr
{
    T* ptr_;
public:
    ScopedPtr();
    ~ScopedPtr();
//Copy and move ctors are removed to be short
}

template <typename T>
ScopedPtr<T>::ScopedPtr() :  ptr_(new T{})
{}

And I want to use it as follows:

struct Numeric_t
{
    int integer_;
    double real_;

    Load_t(int integer = 0, double real = 0) : integer_(integer), real_(real)
    {}
};

struct String_t
{
    std::string str_;

    String_t(std::string str) : str_(str);
    {}
};

int main()
{
    ScopedPtr<Numeric_t> num{1, 2.0};
    ScopedPtr<String_t> str{"Hello, world"};
}

Is there some way to define general ScopedPtr ctor to make Numeric_t and String_t value initialized? Like so:

ScopedPtr<T>::ScopedPtr(//some data, depending on type//) :  ptr_(new T{//some data//})
{}

CodePudding user response:

The usual perfect forwarding comes to mind:

template <typename T>
template <typename... Args>
ScopedPtr<T>::ScopedPtr(Args&&... args) :  ptr_(new T{std::forward<Args>(args)...})
{}
  • Related