Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a C library in a C++ class with type conversion

Tags:

c++

c

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.

like image 740
GWW Avatar asked Jan 21 '23 05:01

GWW


2 Answers

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);
like image 191
Marcelo Cantos Avatar answered Jan 31 '23 12:01

Marcelo Cantos


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.

like image 25
Jack Kelly Avatar answered Jan 31 '23 13:01

Jack Kelly