Re: Conversion error in template specialization
"Matt Messina" <messina@yahoo.com> schrieb im Newsbeitrag
news:1178923124.895884.241500@h2g2000hsg.googlegroups.com...
"Matt Messina" <messina@yahoo.com> schrieb im
Newsbeitragnews:1178836058.052582.81610@q75g2000hsh.googlegroups.com...
Why not overload minimum() instead?
template<size_t N1, size_t N2> inline
const char* minimum(const char (&a)[N1], const char (&b)[N2])
Matthias Hofmann <hofmann@anvil-soft.com> wrote:
On VC++ 2005 Express Edition, I get an ambiguity error if I overload
minimum() as you suggested and call it on two character arrays of 2 bytes
The code only compiles if the arrays ar *not* of identical size. And I
Good point. The problem is that neither overload is more specialized.
The solution, as always, is to provide a disambiguating overload that
is
more specialized than either.
template<class size_t N> inline
const char* minimum(const char (&a)[N], const char(&b)[N])
{ /*...*/ }
Ironically, adding this overload on Sun Workshop 5.8 causes an
ambiguity compile error where there was none before. Good thing
we have a preprocessor.
The disambiguation overload works! :-) Here's the complete (?) list of
overloads necessary for minimum() to work with C-style strings:
// Primary template.
template <class T> inline
const T& minimum( const T& a, const T& b )
{
return a < b ? a : b;
}
// Spezialization for arrays
// of identical size.
template<size_t N> inline
const char* minimum( const char (&a)[N],
const char(&b)[N] )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
// Spezialization for arrays
// of different size.
template<size_t N1, size_t N2> inline
const char* minimum( const char (&a)[N1],
const char (&b)[N2] )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
// Spezialization for non-const pointers.
template <> inline
char* const& minimum( char* const& a,
char* const& b )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
// Spezialization for const pointers.
template <> inline
const char* const& minimum( const char* const& a,
const char* const& b )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
By the way, I have a question concerning these two spezializations:
template<size_t N> inline
const char* minimum( const char (&a)[N],
const char(&b)[N] );
template<size_t N1, size_t N2> inline
const char* minimum( const char (&a)[N1],
const char (&b)[N2] );
Are these spezializations *partial* ones? They have a template parameter
list, like partial spezializations do, but the parameters are only used to
specify the *size* of the arrays, not their *type* - or is the size of an
array part of its type?
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]