Overloading function with char and uint8_t types

Viewed 78

To implement a basic interface for an LCD I need to write the function print for all basic types. I need to write

void print(char c);

and also

void print(uint8_t c);

The first function tells: "I want to write the character c", and the second tells "I want to write the number c". These 2 functions have different meanings, so I need both of them.

The problem is that uint8_t is a typedef of char. If I call

print(20u);

the compiler gives an error because it doesn't know which version of print to choose.

My question is: How to solve this problem?

My solutions:

  1. Define 2 differents functions:
void print(char c);
void print_number(uint8_t x);
void print(uint16_t x);
...

The problem with this solution is that you have to remember that when you want to print an uint8_t you have to call print_number. This complicate all the generic code that I need to write. I don't think is 'the solution'.

  1. Write my proper class uint8_t and instead of using the standard uint8_t use my own version. This solution has different problems:

    • I don't think is a good idea to have an alternative to the standard type uint8_t.
    • If I write my own version of uint8_t, for instance, Uint8_t for consistency I have to write all the other types also (Uint16_t, Uint32_t, ...) and I don't like that too.
  2. ??? Any ideas?

Thanks.

1 Answers

Ok so this might not be the solution you're looking for, but if you type cast while passing the parameter, it works.
print((char) 20u) will call the print(char c)
and
print((uint8_t) 20u) will call the print(uint8_t c)

Related