递归模板类型
recursive template types
我想使以下代码片段正常工作
typedef boost::function<result_type ()> functor_type;
typedef boost::variant<int, functor_type> result_type;
两种类型相互依赖,如何打破循环依赖?
动机
基本上,我想在 c++ 中实现尾部调用,如下所示
template<typename ResultT>
struct TailCall
{
typedef ResultT result_type;
typedef boost::function<ret_type ()> continuation_type;
typedef boost::variant<result_type, continuation_type> ret_type;
TailCall(const continuation_type& init) : next(init) {}
result_type operator()()
{
while (true) {
ret_type r = next();
result_type *result = boost::get<result_type>(&r);
if (result)
return *result;
else
next = boost::get<continuation_type>(r);
}
}
private:
continuation_type next;
};
TailCall<int>::ret_type fibonacci_impl(int term, int val, int prev)
{
if (term == 0) return prev;
if (term == 1) return val;
return boost::bind(fibonacci_impl, term-1, val+prev, val);
}
int fibonacci(int index)
{
TailCall<int> fib(boost::bind(fibonacci_impl, index, 1, 0));
return fib();
}
Boost 变体有两个特定的实用程序(recursive_variant 和 recursive_wrapper)来做到这一点。
下面是一个使用 recursive_wrapper
struct functor_type;
typedef boost::variant<int,
boost::recursive_wrapper<functor_type> > result_type;
struct functor_type : public boost::function<result_type()> {
using boost::function<result_type()>::boost::function<result_type()>;
};
请看boost::recursive_variant
.
Boost.Spirit示例中的一个例子:
struct mini_xml;
typedef
boost::variant<
boost::recursive_wrapper<mini_xml>
, std::string
>
mini_xml_node;
struct mini_xml
{
std::string name; // tag name
std::vector<mini_xml_node> children; // children
};
}
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 此递归模板类型定义是否有效C++?
- 递归函数的返回类型推导
- 在迭代模板类型列表时无法停止递归
- 如何使用common_type和模板递归类型重载运算符+
- C++ 相互递归的变体类型(再次)
- C++ 引用类型作为递归函数参数
- 我的编辑距离递归代码中的字符类型有问题
- 区分递归类型的结合
- 具有类型名的模板的递归实例化
- C++ 递归函数类型
- 是否有一个术语来表示"single mutex deadlock"(具有非递归互斥锁的死锁类型情况)?
- C 递归类型定义
- 我如何实现递归函数的模板,该模板允许C 中的许多不确定数据类型的参数
- 用类型的递归继承获得Variadic模板的阴影成员
- 前向声明不完整类型,递归
- C++:类型别名中的递归依赖关系
- 递归中不同参数类型的变元模板函数
- C 模板递归以检查std :: tuple中的类型