如何从结构中提取最高索引的专业化?

Meh*_*dad 10 c++ templates sfinae template-specialization template-meta-programming

我正在尝试做一些模板元编程,我发现需要"提取"某种类型的某种结构的特化的最高指数.

例如,如果我有一些类型:

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> { };
};
Run Code Online (Sandbox Code Playgroud)

那我怎么能写一个像这样的元函数:

template<class T>
struct highest_index
{
    typedef ??? type;
    // could also be:   static size_t const index = ???;
};
Run Code Online (Sandbox Code Playgroud)

给我D一个在上面的任意结构中专门的最高索引,而不需要结构明确声明计数?

Naw*_*waz 4

这是第一个为您提供定义专门化的最大索引的版本。由此,你就会得到对应的类型!

执行:

template<class T>
struct highest_index
{
  private:
     template<int i>
     struct is_defined {};

     template<int i>
     static char f(is_defined<sizeof(typename T::template D<i>)> *);

     template<int i>
     static int f(...);

     template<int i>
     struct get_index;

     template<bool b, int j>
     struct next
     {
        static const int value = get_index<j>::value;
     };
     template<int j>
     struct next<false, j>
     {
        static const int value = j-2;
     };
     template<int i>
     struct get_index
     {
        static const bool exists = sizeof(f<i>(0)) == sizeof(char);
        static const int value = next<exists, i+1>::value;
     };

    public:
     static const int index = get_index<0>::value; 
};
Run Code Online (Sandbox Code Playgroud)

测试代码:

#include <iostream>

struct A
{
    template<unsigned int> struct D;
};
template<> struct A::D<0> { };
template<> struct A::D<1> { };

struct B
{
    template<unsigned int> struct D;
};
template<> struct B::D<0> { };
template<> struct B::D<1> { };
template<> struct B::D<2> { };


int main()
{
    std::cout << highest_index<A>::index << std::endl;
    std::cout << highest_index<B>::index << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
Run Code Online (Sandbox Code Playgroud)

现场演示。:-)