C++递归模板类型推导

6

我对模板元编程很感兴趣。在下面的代码中,我试图使用一些模板递归来找到一个无符号整数类型,该类型足够大,可以在编译时指定要容纳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

编辑:
我发现了一个我之前错过的帖子:
自动选择足够大的变量类型来保存指定的数字

它指向了boost中的一个答案(他们总是在那里):
boost_integer

这应该解决我的实际需求和智力好奇心。


@mfontanini 你能详细说明一下吗? - TractorPulledPork
1个回答

2
你的问题在于 _type::type 的计算结果是 std::conditional<...>::type,而非 FindIntegralType2<...>::type。将其改为 typedef typename _type::type::type type; (太多的 type x_X)。这样应该能解决你的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接