c++ - 如何从结构中提取最高索引的特化?

标签 c++ templates template-specialization template-meta-programming sfinae

我正在尝试进行一些模板元编程,我发现需要“提取”某种类型的某种结构的特化的最高索引。

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

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> { };
};

然后我如何编写这样的元函数:

template<class T>
struct highest_index
{
    typedef ??? type;
    // could also be:   static size_t const index = ???;
};

给我最高索引的D,它已经在像上面那样的任意结构中专门化,没有要求结构明确声明计数?

最佳答案

这是第一个为您提供定义特化的最大索引的版本。由此,您将获得相应的类型!

实现:

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; 
};

测试代码:

#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;
}

输出:

1
2

Live demo . :-)

关于c++ - 如何从结构中提取最高索引的特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14210378/

相关文章:

c++ - 模板特化 'on the fly'

python - 如何在 bottlepy 模板中做循环?

c++ - 缓冲区溢出不影响 const 变量?

c++ - 一次对两个 vector 进行排序?

c++ - 模板类与非模板类的循环依赖

c++ - 为什么我们使用非类型模板参数?

c++ - 使用模板特化来比较指针引用

c++ - 乘以 10 的倍数时丢失 double

c++ - 力扣 65 : Valid Number (C++)

c++ - 从构造函数参数推断 std::set 的 Compare 类型