是否可以将数据传递到没有指向变量的指针的情况下的 void 指针中
Can you pass data into a void pointer without a pointer to a variable
抱歉,如果标题有点混乱,但我有一个关于我的实体属性系统的问题。
注册属性后,将其放入以下unordered_map:
std::unordered_map<std::string, void*> m_attributes;
下面是注册属性的实现
void registerAttribute(const std::string& id, void* data)
{
m_attributes[id] = data;
}
以及使用它的示例:
std::shared_ptr<int> health(new int(20));
registerAttribute("health", health.get());
我希望能够做的是:
registerAttribute("health", 20);
我不想制作指向数据的指针,因为它很烦人而且代码臃肿。有什么方法可以实现我想要的吗?
谢谢!
采取措施键入您可能希望使用的 Boost::any:
#include <iostream>
#include <map>
#include <boost/any.hpp>
typedef std::map<std::string, boost::any> any_map;
int main(int argc, char *argv[]) {
any_map map;
map.insert(any_map::value_type("health", 20));
std::cout << boost::any_cast<int>(map.begin()->second) << 'n';
return 0;
}
为了获取某物的地址以利用指向它的指针作为void*
,必须有一个可以使用的对象。 void*
的值只是保存数据的存储器的地址。 表达式20
不满足此要求,因为它的存储将在表达式之后消失。
根据地图中值所需的通用性,您可以简化值类型的声明。 如果它们真的总是int
那么使用它。 否则,您可以考虑使用 boost::variant
或 boost::any
之类的内容在地图中创建更常规的值类型。
相关文章:
- 指针变量在 cout 函数中不起作用
- 如何将指针变量作为引用参数传递?
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 我试图了解在异或操作后指针变量正在更改
- 调用带有指针对象错误的指针变量
- 如何在 cuda 中将结构的指针变量从主机复制到设备
- 非指针变量和类成员上的新放置
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- 全局外部指针变量在 DLL 中不可见
- 如何访问在 c++ 中在类内声明的结构类型指针变量?
- C++ 中指针变量的内存释放
- 使用指针变量打印特定的数组变量
- 如何使用构造函数初始化内存地址(指针变量)?
- 如何释放为指针变量本身提供的内存?
- 如果地址已知,如何获取指针变量的名称
- 如何处理参数中的基类和指针变量
- 指针变量 在数组中定位零
- 隐式指针变量,在自动定义中具有另一个指针变量
- 为什么可以将Char指针变量初始化为字符串,而INT指针变量不能初始化到整数数组
- 错误 C4703 可能未初始化的局部指针变量'y'使用