boost::variant - get vector property of members

眉间皱痕 提交于 2019-12-12 03:39:08

问题


I am stuck :). I have two-level hierarchy, each level has child nodes. The goal is to use this structure to populate gui tree. I am trying to access child nodes of variant members in a generic manner. Following code does not compile, using 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;
}

回答1:


Your visitor has an implicit return type of void (the template argument is missing).

Here's taking the opportunity to remove the base class as it's no longer needed in most c++11 code bases:

Live On 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;
}


来源:https://stackoverflow.com/questions/37166181/boostvariant-get-vector-property-of-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!