是否可以将数据传递到没有指向变量的指针的情况下的 void 指针中

Can you pass data into a void pointer without a pointer to a variable

本文关键字:指针 变量 情况下 void 数据 是否      更新时间:2023-10-16

抱歉,如果标题有点混乱,但我有一个关于我的实体属性系统的问题。

注册属性后,将其放入以下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::variantboost::any 之类的内容在地图中创建更常规的值类型。