[英]Template class in std::array
Is it possible to add a template class inside std::array without specifying the typename? 是否可以在std :: array中添加模板类而不指定类型名? I mean.
我的意思是。
template<typename T>
class MyClass
{
...
}
std::array<MyClass *> arr;
The reason is that I have a kind of storage that accepts all classes that derives from MyClass
but the problem with the template class is that I need to specify the typename, then the class need to be like that: 原因是我有一种可以接受从
MyClass
派生的所有类的存储,但是模板类的问题是我需要指定类型名,然后该类必须像这样:
class Storage
{
...
private:
std::array<MyClass<TYPE GOES HERE> *> arr;
}
And I want something more or less like this: 我想要这样的东西:
class Storage
{
...
private:
std::array<MyClass *> arr;
}
This way I can add any class that derives from MyClass. 这样,我可以添加任何派生自MyClass的类。
Is there a way for doing that? 有办法吗?
One option is to create a base class from which MyClass
derives and let the array store pointers to the base class. 一种选择是创建一个派生
MyClass
的基类,并让数组存储指向该基类的指针。
struct MyBase
{
virtual ~Base() {}
};
template<typename T>
class MyClass : public MyBase
{
...
}
std::array<MyBase*> arr;
The reason is that I have a kind of storage that accepts all classes that derives from MyClass
原因是我有一种可以接受从MyClass派生的所有类的存储
You cannot create a class that derives from MyClass
, you can create a class that derives from MyClass<int>
for example etc. So solutions that I see are: 您不能创建派生自
MyClass
的类,而可以创建派生自MyClass<int>
,例如,等等。因此,我看到的解决方案是:
MyClass
derived from non template BaseClass
and keep pointer to BaseClass
MyClass
从非模板BaseClass
派生,并保持指向BaseClass
指针 MyClass
non template and create a template class that derives from it. MyClass
非模板,并创建一个从其派生的模板类。 (this is technically the same as the first) void *
and cast it to specific MyClass<>
on usage, this is error prone though and not recommended. void *
并在使用时将其MyClass<>
为特定的MyClass<>
,但这很容易出错,因此不建议这样做。 boost::any
or boost::variant
(using boost::variant
would be pretty complicated though boost::any
或boost::variant
(使用boost::variant
会很复杂
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.