I'm slowly learning to be a better C++ programmer and I'm currently debating the best way to implement a wrapper for a C library. The library is a wrapper around a compressed file format that can store tags of various types (char *, char, double, float, int32_t). The types are stored as uint8_t* and there are a bunch of auxiliary methods to convert these tags to their proper type. For example:
char tag2char(const uint8_t *v);
char* tag2string(const uint8_t *v);
uint32_t tag2int(const uint8_t *v);
and so forth.
I don't have a lot of experience with templates, but would it be worth wrapping those methods in a template function in a similar fashion to what boost program options does? ie. wrapper[tag].as<uint32_t>();
or should I just implement the each of the tag conversion methods and let the user call the appropriate method on his/her own? or is there a better way I could handle this?
Thanks for the help.
You can use templates for this, and it doesn't require a wrapper class. Just specialise a function template:
template <typename T>
T tag_to(const uint8_t *v);
template <>
char tag_to<char>(const uint8_t *v) { ... }
template <>
char* tag_to<char*>(const uint8_t *v) { ... }
template <>
uint32_t tag_to<uint32_t>(const uint8_t *v) { ... }
...
uint32_t i = tag_to<uint32_t>(tag);
The template approach sounds reasonable, since you'll have to put the name of the type somewhere, anyway, unless you pass by reference (yuck).
I don't support passing by reference because it makes functions less-than-useful as subexpressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With