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