简体   繁体   中英

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. 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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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