samedi 13 août 2022

Value initialization of template object using new

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//})
{}

Aucun commentaire:

Enregistrer un commentaire