C ++递归模板类型推导

时间:2012-05-23 22:38:41

标签: c++ templates recursion template-meta-programming

我有兴趣学习一些关于模板元编程的知识。在下面的代码中,我试图找到一个足够大的无符号整数类型,用于保存在编译时指定的N位,使用一些模板递归。

template <typename T>
struct NextIntegralType
{
};

template <>
struct NextIntegralType<void>
{
    typedef unsigned char type;
};

template <>
struct NextIntegralType<unsigned char>
{
    typedef unsigned short type;
};

...More type 'iteration' here...

template<size_t BITS, typename T>
struct FindIntegralType2
{
    typedef std::conditional<BITS <= sizeof(typename T::type)*8, T, FindIntegralType2<BITS, NextIntegralType<typename T::type>>> _type;
    typedef typename _type::type type;
};

template<size_t BITS>
struct FindIntegralType
{
    typedef typename FindIntegralType2<BITS, NextIntegralType<void>>::type type;
};

当我声明一个变量并为其赋值时......

FindIntegralType<15>::type test(4000);

我得到以下内容:

error: no matching function for call to ‘FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(int)’
note: candidates are:
note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2()
note:   candidate expects 0 arguments, 1 provided
note: constexpr FindIntegralType2<15u, NextIntegralType<unsigned char> >::FindIntegralType2(const FindIntegralType2<15u, NextIntegralType<unsigned char> >&)
note:   no known conversion for argument 1 from ‘int’ to ‘const FindIntegralType2<15u, NextIntegralType<unsigned char> >&’

似乎我的递归不是'解开'。有人能指出我正确的方向吗?

注意:我正在使用 GCC 4.6

修改:
我找到了一篇之前错过的帖子:
Automatically pick a variable type big enough to hold a specified number

哪个指向boost的答案(他们总是在哪里):
boost_integer

这应该解决我的实际需要和求知欲。

1 个答案:

答案 0 :(得分:2)

您的问题是_type::type评估为std::conditional<...>::type,而不是FindIntegralType2<...>::type。将其更改为typedef typename _type::type::type type;type x_X太多)。这应该可以解决你的问题。