boost::variant - 获取成员的向量属性 [英] boost::variant - get vector property of members
本文介绍了boost::variant - 获取成员的向量属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被卡住了:).我有两级层次结构,每个级别都有子节点.目标是使用这个结构来填充 gui 树.我正在尝试以通用方式访问变体成员的子节点.以下代码无法编译,使用 vs2013.我将感谢您的帮助和/或建议关于设计变更.
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;
}
推荐答案
您的访问者的隐式返回类型为 void
(缺少模板参数).
Your visitor has an implicit return type of void
(the template argument is missing).
这里借此机会删除基类,因为在大多数 c++11 代码库中不再需要它:
Here's taking the opportunity to remove the base class as it's no longer needed in most c++11 code bases:
#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;
}
这篇关于boost::variant - 获取成员的向量属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文