C++存储泛型 T 类型类的向量
C++ vector storing generic T type classes
我有一个需要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>Foo
或template<class T>std::vector<Foo<T>>
根本不是类型。它们可以被视为类型的布局。
如果您确实需要在一个容器中存储完全不同的类型,请使用类型擦除方法。例如,来自 C++17 STL 的容器std::any
。看个例子。
相关文章:
- C++中函数的向量返回类型引发错误
- 具有 STL 向量类型成员的类的复制内存
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- 是否可以有一个模板函数,可以将向量和非向量类型都作为参数
- 具有基元类型的模板向量类型
- 在索引和值类型上参数化的惯用向量类型
- 使用迭代器成员函数是否仅适用于某些向量类型"empty()"?
- 通过glUniform 将 GLM 的向量类型传递给 OpenGL
- 尝试将用户定义的向量类型插入用户定义的类型向量
- 使用类作为向量类型时出错 - "Undeclared identifier"
- 在C++中,当两个向量类型不同时,如何将值存储到向量内部的向量中
- 如何访问和存储向量类型的结构成员
- 按参数中的向量类型重载函数
- boost::variant:具有递归向量类型的奇怪行为
- LLVM 传递计数向量类型指令
- 用异构boost::融合向量类型数据填充std::vector
- 如何定义自定义类的向量类型
- 真正的动态向量类型
- 如何在类的属性/变量中使用组合类作为向量类型
- 更快地删除向量类型