I was wondering, why can’t there be a void data type that is not a pointer?
Surely you could get past the whole determined size thing by having
void4
void8
void32
And then only being allowed to ‘cast’ a void data type to another class if its size is equal or under to the classes size.
Is there something that I’m missing, or does the C++ committee just consider it bad practise?
EDIT:
I haven’t explained myself very well, so I’ll give an example of its use:
main()
{
/*
Lets make a list of unknown elements
std::string is 8 bytes, and float is 4
bytes, so we'll reserve 8 byte sequences
*/
vector<void8> elements;
elements.push_back((void8) string("First string element"));
elements.push_back((void8) float(5.76) );
elements.push_back((void8) string("Third string element"));
// Ect.
cout << (string) elements[0];
cout << (float) elements[1];
cout << (string) elements[2];
cout << (float) elements[2]; // Garbage
void1 data;
data = (void1) bool(1);
data = (void1) unsigned int(80094); // Error, not enough size
}
Its named void because you don’t know what type it is currently storing, similar to the void pointer.
In a strongly typed language, all data has a type, so there is no concept of “void” as a datatype. In C and C++, it’s meanings are either “no data” (as a return value), or “data whose type you don’t know” (as a pointer target).
You are proposing an in-between state of “data whose type you don’t know but whose size you do”, presumably as an opaque version of a type you pass by value. Besides being rather a dangerous thing to do (since you have to manually update all the code using the opaque type when you change the size of the real type), this can already be done without adding weird extensions to the language, for example:
This could be used in conjunction with
reinterpret_castto pass POD types around as opaque lumps, in much the way you suggest. Using it with non-POD types is even more likely to invoke undefined behaviour than usingvoid*to refer to non-POD types.It would be safer and more idiomatic to handle opaque types as pointers or references to named types that have been declared but not defined, or something like
boost::anyif you want value semantics. There’s rarely a need to use “void” as a placeholder type in C++.