How to implement a stack using array that supports items of different type.
e.g. It should operate on characters, integers, floats and doubles.
I have implemented it using void pointers. Below is the C implementation:
void push( void** stack, int* top, void* data, size_t size )
{
unsigned i;
++*top;
stack[*top] = malloc( size );
for( i = 0; i < size; ++i )
( (char*)stack[*top] )[i] = ( (char*)data )[i];
}
int main()
{
void* stack[10];
int top = -1, data = 10;
char ch = 'a';
push( stack, &top, (void*)&data, sizeof( int ) );
push( stack, &top, (void*)&ch, sizeof( char ) );
printf( "%d ", *(int*)stack[0] );
printf( "%c ", *(char*)stack[1] );
return 0;
}
The code works fine for me.
The problem with the above implementation is that the type of data must be known before-hand.
Does there exists a way to implement it without knowing prior information about type of data to be operated [ I know it is not possible in C, Can we do it in C++, if Yes, How? ]?
If I understand your requirement, you can use
boost::anyto achieve this in C++.As others have suggested, you can use RTTI to determine the type of the item in the stack. The example below demonstrates an output routine that does this.