Wrapping a C library in a C++ class with type conversion
c, c++
Solution
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);
Problem
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.