简体   繁体   English

为模板参数类提供构造函数而无需继承

[英]Supplying constructor for template parameter class without inheritance

I have a C++ class template. 我有一个C ++类模板。 It takes a template parameter class T and stores an object of type T as a private member accessible through a method called data(). 它采用模板参数类T,并将类型T的对象作为私有成员存储,该私有成员可通过名为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. 我希望我的类模板提供一个方便的构造函数,该构造函数考虑类型T。例如,一个构造函数将T的某些字段作为参数,并使用其值初始化封装的T对象。

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. 一种方法是让用户从模板实例中派生并在其中添加自己的构造函数,但自然地,我更希望有一种提供ctor的方法,而无需让用户编写派生类。

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: 现在,如果用户想要方便的构造函数,则必须派生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. 我阅读了一些C ++ 11的内容,并想到了类似STL的构造函数模板具有std :: list :: emplace()方法集的方法,但是我不确定什么是常见的最佳实践方法。

Yeah, C++11 variadic perfect forwarding is what you want: 是的,您想要的是C ++ 11可变参数完美转发:

template <class T>
class Templ
{
public:
     template<typename... Args>
     explicit Templ(Args&&... args) : obj(std::forward<Args>(args)...) {}

     T& data();
     const T& data() const;
private:
     T obj;
};

This forwards any argument of the Templ constructor to the T constructor. 这会将Templ构造函数的任何参数转发到T构造函数。

But I'm wondering, why even have this class at all? 但是我想知道,为什么还要上这堂课呢? What are you trying to do? 你想做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM