c++ - 递归模板类型

标签 c++

我想让下面的代码片段工作

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()>;
};

关于c++ - 递归模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875568/

相关文章:

c++ - 如何更改窗体上所有控件的标题? [C++ 生成器]

c++ - 基于迭代器构造boost优先级队列

c++ - 基于范围用于原始类型

c++ - 映射/设置迭代器不可递增

c++ - 可变参数模板仿函数调用

c++ - 使用自定义数据类型输入参数调用方法时 open62541 客户端失败

c++ - 捕获鼠标光标图标 C++

java - 我可以使用 CORBA/RMI 制作实时音频流吗?

c++ - 如何通过 JNI/NDK 获取 Android 应用程序中使用的 C++ 库的日志行(printf、cout 等)的控制台输出

c++ - 用于生成 C++ 代码大纲/ map 的工具 - 有这样的东西吗?