C++存储泛型 T 类型类的向量

C++ vector storing generic T type classes

本文关键字:向量 类型 存储 泛型 C++      更新时间:2023-10-16

我有一个需要T类型值的Foo类。我还想将它们存储在向量中。我尝试了几种方法,但没有找到任何解决方案。请查看下面的源代码,以了解我想要实现的目标。

#include <iostream>
#include <vector>
template<class T> class Foo
{
public:
T getVar(T var)
{
return var;
}
};
int main()
{
template<class T>
std::vector<Foo<T>> foos;
Foo<int> foo1;
Foo<double> foo2;
foos.push_back(foo1); // doesn't work this way
foos.push_back(foo2);
return 0;
}

如前所述Foo<int>Foo<double>是不同的类型。同时template<typename T>Footemplate<class T>std::vector<Foo<T>>根本不是类型。它们可以被视为类型的布局。

如果您确实需要在一个容器中存储完全不同的类型,请使用类型擦除方法。例如,来自 C++17 STL 的容器std::any。看个例子。