[英]Is it ane analogue to <?> generics in C++?
For example i have templated structure例如我有模板化结构
template <class T>
struct Event {
T args;
int32_t coordinate;
};
And for example i want to store Event<int32_t>
and Event<std::vector<int32_t>>
in one vector.例如,我想将Event<int32_t>
和Event<std::vector<int32_t>>
在一个向量中。 Is there any analog to generics from other languages like: std::vector<Event<?>>
?是否有与其他语言的泛型类似的东西,例如: std::vector<Event<?>>
?
UPD for all, who need to understand what i need to do: i have many events, which have different types of arguments.所有需要了解我需要做什么的人的UPD :我有很多事件,它们具有不同类型的参数。 For example some events may have int32_t
as arg
, some std::vector<int32_t>
, some Event<int32_t>
, etc...例如,某些事件可能将int32_t
作为arg
、某些std::vector<int32_t>
、某些Event<int32_t>
等...
Comment by @HolyBlackCat @HolyBlackCat 的评论
The classical approach to this is inherit all
Event<T>
from a single non-template base class, then storeunique_ptr
s to that base in thevector
.对此的经典方法是从单个非模板基类继承所有Event<T>
,然后将unique_ptr
s 存储到vector
中的该基类。
This is how you would do it.这就是你要做的。
#include <vector>
#include <cstdint>
#include <memory>
struct EventBase
{
virtual ~EventBase() = default;
};
template <class T>
struct Event : public EventBase {
T args;
std::int32_t coordinate;
};
int main()
{
std::vector<std::unique_ptr<EventBase>> v;
v.emplace_back(new Event<int>());
v.emplace_back(new Event<double>());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.