Re: How to default an undefined operation?
Am 05.09.2012 20:15, schrieb Daniel Kr?gler:
There are several approaches possible. E.g. you could define a helper
traits that evaluates to true, if the expression decltype(U() - U())
is well-formed. In this case, you use the specialization that computes
the difference type from this decltype, otherwise you would fallback
to your version that has a default difference type (or uses other
means to compute it).
Here is an example of a possible approach. Within this example I also
branch for scoped enums and return the underlying type instead (It is
important that both specializations are mutually exclusive because none
is more specialized than the other):
#include <type_traits>
template<typename U, typename Enable = void>
struct helper
{
typedef typename U::differenceType differenceType;
};
template<class T>
struct check
{
typedef void type;
};
template<typename U>
struct helper<U, typename check<decltype(U() - U())>::type>
{
typedef decltype(U() - U()) differenceType;
};
template<class T, bool = std::is_enum<T>::value>
struct is_scoped_enum :
std::integral_constant<bool, !std::is_convertible<T, int>::value>
{
};
template<class T>
struct is_scoped_enum<T, false> : std::false_type
{
};
template<typename U>
struct helper<U, typename std::enable_if<is_scoped_enum<U>::value>::type>
{
typedef typename std::underlying_type<U>::type differenceType;
};
template<typename T>
struct element
{
typedef typename helper<T>::differenceType differenceType;
};
HTH & 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! ]