如何将对象与其类型关联
How to associate object with its type
我正在尝试用C++创建一个统计系统,它将允许我将字符串与任意类型的值相关联。目前,我使用了一个跟踪类型的enum
和一个指向对象的void *
,但这需要我为我想要支持的所有类型生成单独的if
语句。我想拥有它,这样我就可以使用某种模板支持任何任意类型。我已经创建了一些可以工作的测试代码,但也存在一些问题:
class Test {
std::type_index type;
void *value;
public:
template <typename T>
Test(T val) : type(typeid(val)) {
T *val_p = new T;
*val_p = val;
value = (void *)val;
}
Test() : type(typeid(void)) {
value = nullptr;
}
~Test() {
//no idea how I could make this work
}
template <typename T>
T get() {
if (std::type_index(typeid(T)) == type) {
T *val_p = (T *)value;
return *val_p;
} else {
throw std::bad_typeid();
}
}
};
到目前为止,我所做的工作是有效的,但我认为不可能实现析构函数或复制/移动构造函数。重点是我想把这些都存储在一个std::unordered_map
中,所以我不能(AFAIK)只创建一个模板类然后从那里开始。那么,有可能做我想做的事情吗?如果有,我该怎么做?
根据GManNickG的建议,我选择boost::any
,因为它与我想要的最相似。
我还没有将其实现到代码中,但基本结构将大致如下:
#include <typeinfo>
#include <boost/any.hpp>
class Statistic {
boost::any value;
public:
template <typename T>
Statistic(T val) : value(val) {}
Statistic() : value() {}
template <typename T>
bool checkType() {
return typeid(T) == value.type();
}
//Will cause an exception if the type doesn't match
//Caller should check type if unsure
template <typename T>
T get() {
if (checkType<T>()) {
return boost::any_cast<T>(value);
} else {
//throw some exception
throw bad_any_cast();
}
}
}
这样,我就不需要处理析构函数或复制/移动函数,因为隐式函数将调用boost库已经实现的代码。
编辑:感谢千禧虫指出boost::any
已经存储了std::type_info
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 当前不会命中断点。没有调试器目标代码类型的可执行代码与此文件关联
- 关联容器,比较函数不是元素类型的一部分吗?
- 函数类型定义可以与外部"C"相关联吗?
- MISRA C++规则 14-5-1:在与类型关联的命名空间中声明的泛型函数模板的名称
- C ++ STL 关联容器和用户定义类型
- 检测类型是否为关联容器
- 在C API中定义了一个类型,如何将其与命名空间中的C++类相关联
- 使用具有自定义比较类型的关联容器时出现的问题
- 如何将对象与其类型关联
- 用于将静态字符串常量与类型相关联的类型特征模式
- 为什么 c++ 指针 * 与声明的变量相关联,而不是类型
- 隐式返回 0 如何与主的返回类型扣除相关联?
- 文件类型以编程关联和文件位置(Windows)
- 当两个模板的类型相关联时,如何使用策略模板
- 如何打印这种类型map的值map
, int>关联[2]