C++递归模板类型推导
C++ recursive template type deduction
我有兴趣学习一些关于模板元编程的知识。在下面的代码中,我试图找到一个足够大的无符号整数类型,以容纳在编译时指定的 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太多)。这应该可以解决您的问题。
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 此递归模板类型定义是否有效C++?
- 递归函数的返回类型推导
- 在迭代模板类型列表时无法停止递归
- 如何使用common_type和模板递归类型重载运算符+
- C++ 相互递归的变体类型(再次)
- C++ 引用类型作为递归函数参数
- 我的编辑距离递归代码中的字符类型有问题
- 区分递归类型的结合
- 具有类型名的模板的递归实例化
- C++ 递归函数类型
- 是否有一个术语来表示"single mutex deadlock"(具有非递归互斥锁的死锁类型情况)?
- C 递归类型定义
- 我如何实现递归函数的模板,该模板允许C 中的许多不确定数据类型的参数
- 用类型的递归继承获得Variadic模板的阴影成员
- 前向声明不完整类型,递归
- C++:类型别名中的递归依赖关系
- 递归中不同参数类型的变元模板函数
- C 模板递归以检查std :: tuple中的类型