JKop <NU**@NULL.NULL> wrote:
Here's two functions, a "const version" and a "non-const version":
char* GetFirstT(char* p)
{
for ( ; *p; ++p)
if ( *p == 't' ) return p;
return 0;
}
const char* GetFirstT(const char* p)
{
for ( ; *p; ++p)
if ( *p == 't' ) return p;
return 0;
}
See how I have to define two functions, is there any handy around that?
The C standard library solves this problem with:
char *strchr(const char *ptr, char ch);
ie. using 'const' in the parameter and non-const in the return type.
This 'minimises the damage', ie. you only have to use casts
(when calling the function I mean, not when implementing it) if
you use it on a const string and assign the result to a 'const char *'.
But since this is C++ we can use a template:
template<typename Iter>
Iter GetFirstT(Iter p)
{
for ( ; ; ++p )
if (*p == 't' || *p == '\0')
return p;
}
Constraints - 'Iter' must be a type for which '++', '==' with a char,
and '*' are valid operations.
Note that I have made a slight change, it returns a pointer to the end
of the string instead of NULL if the 't' is not found. But you could
easily stick to your version, but add the constraint that 'Iter'
must be such that it can have 0 assigned to it.
There have been a couple of objections to this approach raised in
this thread, which I don't understand...
You said "the template is non-const". But it does not make sense
to say that a template is const or not, so I have no idea what you
meant. Are you unaware that you can have GetFirstT<char *> and
GetFirstT<char const *> ?
Pete Becker said "GetFirstT<wchar_t *>" doesn't work. So what?
The original stipulation was only for "char *" and "char const *",
and this example does just fine for them. There are plenty
of examples in the standard library where templates won't work
if you use the wrong types as parameters.