Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding void* in C++

Tags:

c++

I have an application that requires the packing of heterogeneous data in to a single structure. For example, a single structure might contain three floats, two integers and a string. I don't know which fields I'll have until runtime, and the key requirement is that the process be extremely fast. I was planning to use an array of void*, which I can cast to the appropriate type when the message reaches its destination, but is there a better way of doing this? Perhaps using Boost?

like image 273
endian Avatar asked Nov 22 '11 23:11

endian


3 Answers

Perhaps boost_variant will satisfy your needs?

http://www.boost.org/doc/html/variant.html

like image 131
shuttle87 Avatar answered Sep 21 '22 23:09

shuttle87


Could you use the plain old union?

like image 38
Branko Dimitrijevic Avatar answered Sep 18 '22 23:09

Branko Dimitrijevic


I had the same problem. My solution was to define a interface called Data. This Interface did not provide anything except a virtual destructor. All my data-types now inherit from the Data interface. This allows me to define a vector of Data pointers. When I need them I cast them to the actual type, so that I can use them.

This solution avoids the use of void Pointers, by using a marker class instead.

// Marker interface
class Data {
     public:
           virtual ~Data()=0;
}
// Own Datatype
class MyDataType: public Data {
     ...
}
like image 29
tune2fs Avatar answered Sep 20 '22 23:09

tune2fs