如何从结构中提取最高索引的专业化? [英] How to extract the highest-indexed specialization from a structure?
本文介绍了如何从结构中提取最高索引的专业化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做一些模板元编程,我发现需要提取某种类型的某些结构的专业化的最高索引。
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 = ???;
};
给我最高索引 D
推荐答案
这是第一个版本,它为您提供了定义特殊化的最大索引。
This is the first version which gets you the maximum index for which specialization is defined. From this, you will get the corresponding type!
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;
};
测试代码:
Test code:
#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 。 : - )
这篇关于如何从结构中提取最高索引的专业化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文