I have a C++ class template. It takes a template parameter class T and stores an object of type T as a private member accessible through a method called data(). The code below demonstrates it. I’d like my class template to offer a convenient constructor which takes into account the type T. For example, a constructor which takes some of T’s fields as parameters and initializes the encapsulated T object with their values.
One way to do that is having the user derive from the template instantiation and add their own constructors there, but I’d prefer, naturally, to have a way to supply ctors without making the user write a derived class.
template <class T>
class Templ
{
public:
T& data();
const T& data() const;
private:
T obj;
};
Now if a user wants a convenienve constructor, they’d have to derive Templ:
class MyClass : public Templ<MyData>
{
public:
MyClass (int size, MyClass* parent, float temperature, std::string name);
};
I read some C++11 stuff and had ideas about having a constructor template like the STL has std::list::emplace() set of methods, but I’m not sure what’s the common best-practice solution.
Yeah, C++11 variadic perfect forwarding is what you want:
This forwards any argument of the
Templconstructor to theTconstructor.But I’m wondering, why even have this class at all? What are you trying to do?