Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data structure with type-specific, but without template

I have noticed that most (all?) of C++ data structures that can store a user defined type use template:

std::vector<T>, std::unordered_map<T....>, etc.

It seems to me that it is required, otherwise those data-structures will have to return as the sinister pointer void* that users have to cast manually as follows:

std::vector a; 
int b;
a.push_back(b);
static_cast<int>(a.get(0));

Is it possible to not use the template? Are there any other alternative approaches?

Edit: Many comments suggest that without template, it is impossible / impractical. (Thank!)

What if I limited <T> to be a real pointer (e.g. not int/float), will it still be impractical?

like image 550
javaLover Avatar asked Mar 12 '26 19:03

javaLover


1 Answers

Is it possible to not use the template?

Yes. It is possible to define a general data structure, that allows grouping <-- I don't know what verb to use here objects of any type, without using a template.

There is the "C way" (templates do not exist in C). The C way is to use void*. You are apparently already familiar, but for other readers of the answer, void* is a special pointer type, that can point to an object of any type. When you use void* to refer to an object, you essentially throw away all type safety that the language offers.

I don't think there are any non-template containers in the standard library. However, if it is not too much to use the offered templates to instantiate std::vector<void*> or similar, then you can certainly use such template instance to store pointers to any objects.

Templates are strongly preferred to void* because templates do not throw type safety out of the window. Templates are much easier to use correctly.

Not yet. But std::any is planned to be introduced in C++17. It can be used in stead of void*. Using std::any you still throw away compile time type safety, but at least you retain run time safety (you'll get an exception instead of potentially dragons when you have a bug). And unlike void*, std::any manages the memory of the stored object. Note that while std::any is not a template, most of its member functions are.


Are there any other alternative approaches?

Besides templates and void*? Technically, you could also use macros to generate different versions of same program, similarly to instantiating a template. This is sometimes used in C. There is no reason do this in C++, because templates are better in every way.

like image 122
eerorika Avatar answered Mar 15 '26 13:03

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!