I'm trying to do some template metaprogramming and I'm finding the need to "extract" the highest index of a specialization of some structure in some type.
For example, if I have some types:
struct A
{
template<unsigned int> struct D;
template<> struct D<0> { };
};
struct B
{
template<unsigned int> struct D;
template<> struct D<0> { };
template<> struct D<1> { };
};
struct C
{
template<unsigned int> struct D;
template<> struct D<0> { };
template<> struct D<1> { };
template<> struct D<2> { };
};
How can I then write a metafunction like this:
template<class T>
struct highest_index
{
typedef ??? type;
// could also be: static size_t const index = ???;
};
to give me the highest-indexed D
that has been specialized inside an arbitrary struct like the ones above, without requiring the struct to have declared the count explicitly?
This is the first version which gets you the maximum index for which specialization is defined. From this, you will get the corresponding type!
Implementation:
Test code:
Output:
Live demo. :-)
Figured it out with the help from the comments under the question!
Here is my little contribution.
We start off with the existence methods:
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
: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:
So, unfortunately,
highest_index
is not usable and the clang is dang slow (not that gcc appears to be doing better).