简体   繁体   English

boost :: variant-获取成员的矢量属性

[英]boost::variant - get vector property of members

I am stuck :). 我被困住了:)。 I have two-level hierarchy, each level has child nodes. 我有两级层次结构,每级都有子节点。 The goal is to use this structure to populate gui tree. 目标是使用此结构来填充gui树。 I am trying to access child nodes of variant members in a generic manner. 我正在尝试以通用方式访问变体成员的子节点。 Following code does not compile, using vs2013. 使用vs2013,以下代码无法编译。 I'll appreciate the helping hand and/or advise on the design changes. 我将不胜感激,并/或就设计变更提供建议。

#include "stdafx.h"
#include <memory>
#include <string>
#include <vector>
#include <boost/variant.hpp>

class base {};

class A : public base
{
public:
    std::vector<std::shared_ptr<base>> & lst(){ return _lst; }
private:
    std::vector<std::shared_ptr<base>> _lst;
};

class B : public base
{
public:
    std::vector<std::shared_ptr<A>>& lst() { return _lst; }
private:
    std::vector<std::shared_ptr<A>> _lst;
};

using bstvar = boost::variant<A, B>;

class lstVisitor : public boost::static_visitor<>
{
public:
    template <typename T> std::vector<std::shared_ptr<base>>& operator()  (T& t) const
    {
        return t.lst();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    bstvar test;
    auto& lst= boost::apply_visitor(lstVisitor{}, test);

    return 0;
}

Your visitor has an implicit return type of void (the template argument is missing). 您的访客的隐式返回类型为void (缺少模板参数)。

Here's taking the opportunity to remove the base class as it's no longer needed in most c++11 code bases: 借此机会删除基类,因为大多数c ++ 11代码库不再需要该基类:

Live On Coliru 生活在Coliru

#include <memory>
#include <string>
#include <vector>
#include <boost/variant.hpp>

class base {};

using base_vec = std::vector<std::shared_ptr<base> >;

class A : public base {
  public:
    base_vec &lst() { return _lst; }

  private:
    base_vec _lst;
};

class B : public base {
  public:
    base_vec &lst() { return _lst; }

  private:
    base_vec _lst;
};

using bstvar = boost::variant<A, B>;

struct lstVisitor {
    using result_type = base_vec&;
    template <typename T> result_type operator()(T &t) const { return t.lst(); }
};

int main(int argc, char *argv[]) {
    bstvar test { B{} };
    base_vec& lst = boost::apply_visitor(lstVisitor{}, test);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM