Domanda

I have a data class (struct actually) two variables: a void pointer and a string containing the type of the object being pointed to.

struct data{
  void* index;
  std::string type;

  data(): index(0), type("null"){}
  data(void* index, std::string type): index(index), type(type){}};

Now I need to use the object being pointed to, by casting the void pointer to a type that is specified by the string, so I thought of using an std::map with strings and functions.

std::unordered_map<std::string, function> cast;

The problem is that the functions must always have the exact same return-type and can't return a type itself.

Edit: Because I use the data class as a return-type and as arguments, templates won't suffice. (also added some code to show what I mean)

data somefunction(data a){
  //do stuff
  return data();}

Currently, I use functions like this to do the trick, but I thought it could be done more easily:

void functionforstring(data a){
  dynamic_cast<string*>(data.index)->function();}
È stato utile?

Soluzione

Neither thing is possible in C++:

  • Functions cannot return types (that is to say, types are not values).
  • Code cannot operate on objects whose type it doesn't know at compile-time (that is to say, C++ is statically typed). Of course there is dynamic polymorphism via virtual functions, but even with that, the type of the pointer you use to call them is known at compile time by the calling code.

So the operation you want, "convert to the pointer type indicated by a string" is not possible. If it were possible, then the result would be a pointer whose type is not known at compile time, and that cannot be.

There's nothing you could do with this "pointer of type unknown at compile time", that you can't do using the void* you started with. void* pretty much already is what C++ has in place of a pointer to unknown type.

Altri suggerimenti

While it's not possible to return a type from a function, you could use typeid to get information about the object, and use the string returned by typeid(*obj).name() as an argument to your constructor.

Keep in mind that this string would be implementation defined, so you would have to generate this string at runtime for every type that you might possibly use in the program in order to make your unordered_map useful.

There is almost certainly a much simpler and more idiomatic way to accomplish your goal in C++, however. Perhaps if you explained more about the goals of the program, someone might be able to suggest an alternative approach.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top