tags:

views:

111

answers:

3

Hello everyone,

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.

+1  A: 

In C++ you can have functions with the same name but different parameters. The function you mentioned are perfect candidates for overloading. No need for templates. When all functions have the same name the user of your wrapper library has less things to remember.

Dialecticus
You can't overload if the functions only differ on return type. You'd have to pass by reference and that's ugly.
Jack Kelly
You can't overload these, because they all have the same signature.
Marcelo Cantos
OMG, I totally missed it.
Dialecticus
+4  A: 

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.

Jack Kelly
+4  A: 

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);
Marcelo Cantos