Tra*_*ork 6 c++ recursion templates 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;
};
Run Code Online (Sandbox Code Playgroud)
当我声明一个变量并为其赋值时...
FindIntegralType<15>::type test(4000);
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:
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> >&’
Run Code Online (Sandbox Code Playgroud)
似乎我的递归不是'解开'.谁能指出我正确的方向?
注意:我正在使用GCC 4.6.
编辑:
我发现了一个我之前错过的帖子:
自动选择一个足够大的变量类型来保存指定的数字
这指向了boost中的答案(它们始终存在):
boost_integer
这应该解决我的实际需要和求知欲.
你的问题是_type::type评估为std::conditional<...>::type,而不是FindIntegralType2<...>::type。将其更改为typedef typename _type::type::type type;(太多typex_X)。这应该可以解决你的问题。