'Overloading function with char and uint8_t types
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:
- 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'.
Write my proper class
uint8_tand instead of using the standarduint8_tuse 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_tfor consistency I have to write all the other types also (Uint16_t,Uint32_t, ...) and I don't like that too.
- I don't think is a good idea to have an alternative to the standard type
??? Any ideas?
Thanks.
Solution 1:[1]
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)
andprint((uint8_t) 20u) will call the print(uint8_t c)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Batman |
