boost :: variant递归麻烦

Voi*_*oid 5 c++ boost-variant c++11

有没有办法让这项工作?我希望你能得到这个想法,我试图通过递归对创建一个列表

#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;
}
Run Code Online (Sandbox Code Playgroud)

bdo*_*lan 4

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

但是,您可以通过指针传递它来完成此操作。例如:

struct nil { };

typedef boost::make_recursive_variant<nil, 
    std::pair<int, boost::scoped_ptr<boost::recursive_variant_> > >
        variant_list_int;
Run Code Online (Sandbox Code Playgroud)

  • 很抱歉“带来仇恨”有点晚了,可以这么说,但我刚刚从一个相关问题中遇到了这个问题。不需要将指针放入 boost.variant —— recursive_variant 包装器在内部使用 `boost::shared_ptr` ,因此您的“无限大小”声明是错误的。基于堆栈的方案无法得到保证,并且仅当所有构造函数(对于模板参数)都具有 nothrot 构造函数时才使用。您可以在这里阅读更多相关信息:http://www.boost.org/doc/libs/1_46_1/doc/html/variant/design.html#variant.design.never-empty(查找“临时堆备份”) 。 (9认同)