With C++, you should both use function overloading and make sure no one will send you the address of a char.
void ReplaceCharInString(std::string & p_string, char p_a, char p_b)
{
for(size_t i = 0, iMax = p_string.size(); i < iMax; ++i)
{
// replace if needed : p_string[i]
}
}
void ReplaceCharInString(char & p_char, char p_a, char p_b)
{
// replace if needed : p_char
}
template<size_t size>
void ReplaceCharInString(char (& p_string)[size], char p_a, char p_b) ;
{
for(size_t i = 0; i < size; ++i)
{
// replace if needed : p_string[i]
}
}
With only those three functions (and no function taking char *
as its first parameter), no one will be able to call them with a raw char *
:
void foo()
{
char a[4] ;
std::string b ;
char c ;
char * d ;
// initialize a, b, c and d to some values
ReplaceCharInString(a, 'x', 'z') ; // compiles
ReplaceCharInString(b, 'x', 'z') ; // compiles
ReplaceCharInString(c, 'x', 'z') ; // compiles
ReplaceCharInString(d, 'x', 'z') ; // COMPILATION ERROR
}
So there's no way someone will call your function with the address of a single char.
Anyway, in C++, there are very few reasons to use char *
as a string (you would use instead a std::string
), and even less a char *
as an address to a single char (you would use instead a char &
), so no one will complain about the lack of support for char *
in the functions above.