【问题标题】:boost::variant recursive troubleboost::variant 递归问题
【发布时间】:2011-02-08 11:00:46
【问题描述】:

有什么办法可以使这项工作?我希望你能明白,我正在尝试通过递归对创建一个列表

#include <boost/variant.hpp>
#include <utility>

struct nil {};
typedef boost::make_recursive_variant<nil, std::pair<int, boost::recursive_variant_ >>::type list_t;

int main() {
  list_t list = { 1, (list_t){ 2, (list_t){ 3, nil() } } };
  return 0;
}

【问题讨论】:

    标签: c++ c++11 boost-variant


    【解决方案1】:

    没有。 boost::variant 的要点是它具有固定大小,并且不进行动态分配。这种方式类似于联合。递归 boost::variant 必须具有无限大小才能包含其最大可能值 - 显然是不可能的。

    但是,您可以通过指针传递它来做到这一点。例如:

    struct nil { };
    
    typedef boost::make_recursive_variant<nil, 
        std::pair<int, boost::scoped_ptr<boost::recursive_variant_> > >
            variant_list_int;
    

    【讨论】:

    • 抱歉“带来仇恨”有点晚了,可以这么说,但我刚刚从一个相关问题中遇到了这个问题。无需将指针放入 boost.variant —— recursive_variant 包装器在内部使用 boost::shared_ptr,因此您的“无限大小”声明是错误的。不保证基于堆栈的方案,仅当所有构造函数(对于模板参数)都有一个 nothrow 构造函数时才使用。您可以在此处阅读更多相关信息:boost.org/doc/libs/1_46_1/doc/html/variant/…(查找“临时堆备份”)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2011-04-06
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多