Re: Conversion error in template specialization
On 14 Mai, 21:40, Daniel Kr?gler <daniel.krueg...@googlemail.com>
wrote:
I did not deny that. But currently you already overload
minimum (by providing functions templates for char[]
and char const []), so the two specializations show
no real advantage compared to overloading. Or is it
important for you to invoke the functions via explicit
template argument provision? If yes, than you have
to get rid of your overloads, which handle character
arrays, anyway because they would not be invoked
by any explicit type specification!
I think that you can reduce your implementation effort
by taking advantage of the SFINAE technique. Here
a simple example to demonstrate the idea:
#include <cstddef>
#include <cstring>
template <typename T>
struct IsCharSeq {
static const bool value = false;
};
template <>
struct IsCharSeq<char*> {
static const bool value = true;
};
template <>
struct IsCharSeq<const char*> {
static const bool value = true;
};
template <std::size_t N>
struct IsCharSeq<char[N]> {
static const bool value = true;
};
template <std::size_t N>
struct IsCharSeq<const char[N]> {
static const bool value = true;
};
template <bool Enable, typename T>
struct EnableIf {
};
template <typename T>
struct EnableIf<true, T> {
typedef T type;
};
template <class T> inline
typename EnableIf<!IsCharSeq<T>::value, const T&>::type
minimum( const T& a, const T& b )
{
return a < b ? a : b;
}
template <class T1, class T2> inline
typename EnableIf<IsCharSeq<T1>::value &&
IsCharSeq<T2>::value, const char*>::type
minimum( T1 a, T2 b )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
int main() {
char* a = "hui";
const char b[] = "buu";
minimum(a, b);
}
You can even further reduce your own part of that
by using boost::is_convertible, that is along the
lines of:
#include <cstddef>
#include <cstring>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/and.hpp>
template <class T> inline
typename boost::disable_if<boost::is_convertible<const T&, const
char*>, const T&>::type
minimum( const T& a, const T& b )
{
return a < b ? a : b;
}
template <class T1, class T2> inline
typename boost::enable_if<boost::mpl::and_<boost::is_convertible<T1,
const char*>,
boost::is_convertible<T2, const char*> >, const char*>::type
minimum( T1 a, T2 b )
{
return std::strcmp( a, b ) < 0 ? a : b;
}
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]