Here is my little contribution.
We start off with the existence methods:
template <unsigned>
static unsigned char exists_impl(...);
template <unsigned N, typename T>
static auto exists_impl(T const&&) ->
typename std::enable_if<sizeof(typename T::template D<N>),
unsigned char (&)[2]>::type;
template <typename T, unsigned N>
static constexpr bool exists() {
return sizeof(exists_impl<N>(std::declval<T>())) != 1;
}
I believe here that constexpr
and function usage do bring a lot to the table in terms of readability, so I don't use the typical types.
Then, we use a typical binary search (2nd attempt, see first attempt at bottom), at a loss of readability, but to benefit from lazy instantiation, we use partial template specialization and std::conditional
:
template <typename T, unsigned low, unsigned high, typename = void>
struct highest_index_in;
template <typename T, unsigned low>
struct highest_index_in<T, low, low>: std::integral_constant<unsigned, low> {};
template <typename T, unsigned low, unsigned high>
struct highest_index_in<T, low, high, typename std::enable_if<(high == low + 1)>::type>:
std::integral_constant<unsigned, low + exists<T, low+1>()> {};
template <typename T, unsigned low, unsigned high>
struct highest_index_in<T, low, high, typename std::enable_if<(high > low + 1)>::type>:
std::conditional< exists<T, (low+high)/2>(),
highest_index_in<T, (low+high)/2, high>,
highest_index_in<T, low, (low+high)/2> >::type
{};
template <typename T>
static constexpr unsigned highest_index() {
return highest_index_in<T, 0, ~(0u)>::value;
} // highest_index
Demo at liveworkspace, computing highest_index<C>()
is near instantaneous.
First attempt at binary search, unfortunately the compiler need instantiate the function bodies recursively (to prove they can be instantiated) and thus the work it has to do is tremendous:
template <typename T, unsigned low, unsigned high>
static constexpr auto highest_index_in() ->
typename std::enable_if<high >= low, unsigned>::type
{
return low == high ? low :
high == low + 1 ? (exists<T, high>() ? high : low) :
exists<T, (high + low)/2>() ? highest_index_in<T, (high+low)/2, high>() :
highest_index_in<T, low, (high+low)/2>();
} // highest_index_in
template <typename T>
static constexpr unsigned highest_index() {
return highest_index_in<T, 0, ~(0u)>();
} // highest_index
So, unfortunately, highest_index
is not usable and the clang is dang slow (not that gcc appears to be doing better).
` look like, for general type `T` and specialization `S`?– TemplateRex Jan 08 '13 at 08:26