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

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

4

1 回答 1

2

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

于 2012-05-24T01:59:56.667 回答