简体   繁体   中英

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

Sorry if the title is a little bit confusing, but I have a question that regards my entity attribute system.

When an attribute is registered, it's put into this unordered_map:

std::unordered_map<std::string, void*> m_attributes;

Here's the implementation for registering an attribute

void registerAttribute(const std::string& id, void* data)
{
    m_attributes[id] = data;
}

and example of using it:

std::shared_ptr<int> health(new int(20));

registerAttribute("health", health.get());

What I want to be able to do is this:

registerAttribute("health", 20);

I don't want to have to make a pointer to the data because it's annoying and just bloated code. Is there any way to achieve what I want?

Thanks!

Taking steps to type elision you might want to utilize 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;
}

In order to get the address of something to leverage a pointer to it as a void* , one must have an object with which to work. The value of the void* is simply an address to the memory holding the data. The expression 20 doesn't satisfy this requirement because its storage will be gone after the expression.

Depending upon the generality necessary for the values in your map you could simplify the declaration of the value type. If they are really always int then use that. Otherwise, you may consider using something like boost::variant or boost::any for creating more general value types in your map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM