C++递归模板类型推导

C++ recursive template type deduction

本文关键字:类型 递归 C++      更新时间:2023-10-16

我有兴趣学习一些关于模板元编程的知识。在下面的代码中,我试图找到一个足够大的无符号整数类型,以容纳在编译时指定的 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_integer

这应该既解决了我的实际需求,也解决了我的求知欲。

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