C++是否有一些类似C#类型的东西来存储列表/数组中的类类型
Does C++ have some analog of C# Type thing to store Types of classes in list / array?
在C#中,我可以创建这样的List来存储类类型:
List<Type> types_list = new List<Type>();
types_list.add(typeof(int));
types_list.add(typeof(Process)); //and etc
我能在C++中做同样的事情吗?
参见typeid
和type_info
。
请注意,不能使用type_info
类来创建它所代表的类型的新实例,因为C++不支持这样做。
您可以使用boost MPL存储类型列表。示例:
#include <boost mpl stuff>
int main()
{
typedef boost::mpl::vector<char, int> types;
typedef boost::mpl::push_back<types, Process>::type newTypes;
boost::mpl::at_c<newTypes, 2>::type objectOfTypeProcess;
}
除非你知道自己在做什么,否则你真的不应该使用这个库,所以我的例子没有那么具体。无论如何,你可能需要花一些时间来适应mpl。
还可以动态创建实例。鼓舞人心但不完整的代码:
class TypeProxy {
public:
virtual ~TypeProxy() = default;
char* create_default() const { return this->create_default_impl(); }
template <typename T>
static scoped_ptr<TypeProxy> CreateProxy ();
private:
virtual void* create_default_impl() const = 0;
};
// A creator class.
template <typename T>
class Concrete : public TypeProxy {
void *create_default_impl() const {
return new T ();
}
};
// Method to create creator proxies.
template <typename T>
scoped_ptr<TypeProxy> TypeProxy::CreateProxy () {
return scoped_ptr<TypeProxy> (new Concrete<T>());
}
请注意,这只是一些未经测试的临时代码,用于显示操作模式。是否使用scoped_ptr
是有争议的。
你可以更喜欢可变模板(例如,参见C++11中的emplace[_(front|back)]
函数),但它会变得复杂,因为不允许使用虚拟函数模板,但无论如何你都必须传递参数列表。
(旁注:boost::shared_ptr
使用类似的虚拟/模板组合,这就是为什么您可以使用非多态基类和自定义deleter)
相关文章:
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- C++ 将 CIN 值存储到任何类型的数组中
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- 在C++中,如何在变量中正确存储 BYTE 类型?
- 多维数组存储三种不同的数据类型?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 在 JavaScript 中,值的数据类型存储在何处以及如何存储?
- 将Protobuf字节类型存储在二进制文件中
- 如何检查程序是否超过数据类型存储
- 将多调数据类型存储到unique_ptr向量中
- C++元编程:按类型存储整数
- 将多个类型存储到同一个容器中
- 如何打印 boost::any 的向量,当我将元素类型存储在另一个字符串向量中时
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- C++ dynamic_cast vs 将对象类型存储在静态枚举中
- 有没有任何方法可以在运行时将不同的数据类型存储在一个变量中
- 是否可以将Boost uint128_t数据类型存储为原始int类型?
- 使用boost::variant库制作地图.如何以适当的类型存储和显示事物
- 是否可以将对象的类型存储在映射中以进行投射