我正在尝试进行一些模板元编程,我发现需要“提取”某种类型的某种结构的特化的最高索引。
例如,如果我有一些类型:
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/