void * help

Started by
13 comments, last by snk_kid 18 years, 5 months ago
just another example

#include <iostream>#include <vector>using namespace std;void main(){	vector<void*> voidVec;		int i = 5;	float f = 7.7;	double d = 5.5;	char c = 'p';	voidVec.push_back(&i);	voidVec.push_back(&f);	voidVec.push_back(&d);	voidVec.push_back(&c);	cout << *(int*)voidVec[0] << endl;	cout << *(float*)voidVec[1] << endl;	cout << *(double*)voidVec[2] << endl;	cout << *(char*)voidVec[3] << endl;	system("pause");}




Advertisement
Quote:Original post by 31337noob
i am tring to make a script system
that holds the data.


Then you should use something like Boost.Variant or Boost.Any (www.boost.org). You need to be able to find the type of the data later so you can decide how to deal with it (you will probably also want to use something like std::map, since you probably want to bind the values to variables).
it works now.
i fixed it.
thanks for your help.

i am still using vector<void*>
Quote:Original post by 31337noob
i am tring to make a script system
that holds the data.


Even if you where doing this in pure C there is a better solution to void pointers since you are only dealing with a small set of types you could have used a tagged union to simulate variant types. In C++ use boost::variant:

#include <algorithm> // for_each#include <vector>#include <string>#include <iostream>#include <boost/variant.hpp>#include <d3dx9.h>typedef boost::variant<bool, int, float, D3DXCOLOR, D3DXVECTOR3, std::string> script_vari;struct type_printer : boost::static_visitor<> {    template < typename Tp >    void operator()(const Tp&) const {	std::cout << "type is: " << typeid(Tp).name() << '\n';    }};int main() {    std::vector<script_vari> varis;    varis.push_back(true);    varis.push_back(10);    varis.push_back(10.03f);    varis.push_back(std::string("foo"));    varis.push_back(D3DXCOLOR(1.0f, 1.0f, 0.0f, 1.0f));    varis.push_back(D3DXVECTOR3(1.0f, 1.0f, 1.0f));    std::for_each(varis.begin(), varis.end(),		boost::apply_visitor(type_printer()));}


Take note that variant's can be recursive aswell no need to abuse OO here.

This topic is closed to new replies.

Advertisement