we seem to be having a style issue in the team.
We have a string class that has char* and const char* conversion operators
(yes, i know we should be using std::string, please bear with me).
Some people in the team prefer that, when calling code like this:
retval func(..., const char* param, ...);
with an instance of our string class, we use an explicit cast, e.g.
mystring s(whatever);
func(..., (const char*)s, ...);
(as opposed to not using a cast).
Can I please have your opinion on this (good/bad/like/not like)? Insight?
(My purpose, obviously, is to show your responses to the team).
Some times an explicit conversion is needed to select the intended
overload of a function.
For example,
Code:
struct S
{
operator char const* () const { return "Ta da"; }
};
#include <iostream> // std::cout, std::cerr, std::endl
using namespace std;
void foo( void const* ) { cout << "foo receiced void pointer" << endl; }
template< class Char >
void foo( Char const* p ) { cout << "foo says: " << p << endl; }
auto main() -> int
{
foo( S() );
foo( static_cast<char const*>( S() ) );
}
[output]
foo receiced void pointer
foo says: Ta da
[/output]
In particular this is a problem with direct output to standard
iostreams, selecting the void* argument operator<< since implicit
conversion is not considered for template matching.
With that in mind,
* Where an explicit conversion is needed (e.g. as above), express it in
a safe way using static_cast or direct call of the conversion operator.
Do NOT use a C style cast. When the code is maintained the C style cast
can silently change meaning to something rather undesired...
* Where an explicit conversion isn't needed, just use the implicit
conversion, because this string class is used all over the place and
everybody knows about its behavior, and because it minimizes the code
impact of cleaning up those called functions to take string class type
arguments. One doesn't go on pointing out that the Earth is round.
Rather, it sounds pretty silly and gets annoying pretty fast when
someone can't refrain from pointing out the well known roundness of
Earth all the time, whenever there is any kind of reference to Earth.
Of course, as already remarked on in this thread, your firm would be
much better off using std::string. This is not the case for every custom
string class -- they have their uses, and std::string is about the worst
that COULD be standardized. But a class with implicit conversion to
non-const char*, well char based and encouraging uncontrolled outside
modification of its contents, that class sounds as having negative
practical value (creating work), so best ditch it. ;-)
Cheers & hth.,
- Alf