首页 > 解决方案 > C++ boost::get 和访问者

问题描述

我制作了一个boost::variant具有多种类型的向量,如下所示:

std::vector<boost::variant<type1,type2,type3,...and so on>>

在那之后,我做了一个typedef将整个类型重命名为vecTypesVar的变体命名为typesVar

typedef boost::variant<type1,type2,type3,...and so on> typesVar
typedef std::vector<typesVar> vecTypesVar

现在,我已经在该向量上创建了一个 for 循环,并使用了.which我试图为每个类型进行实现的选项。

vecTypesVar type = getTypesData();
for (auto i = 0; i < type.size(); ++i)
{
    switch (type[i].which())
    {
    case 0:
        break;

    case 1:
        break;

    case 2:
        break;
    default: ;
    }
}

所以,问题就在这里开始了,在开关的每一种情况下,我都试图使一个变量与出现的变量类型相同。

例如:

case 0:
    auto data = boost::get<type1>(type[i]);

但我收到一个错误,上面写着:

错误 C2248:“type1::type1”:无法访问在类“type1”中声明的私有成员

我也尝试过使用这样的访问者:模板

class port_visitator : public boost::static_visitor<T>
{
    T operator()(typesVar type) const
    {
        return boost::get<T>(type);
    }
};

并在我的开关中使用它:

case 0:
   auto data = apply_visitor(port_visitator<type1>(), type[i]);

但我收到了同样的错误:

错误 C2248:“type1::type1”:无法访问在类“type1”中声明的私有成员

编辑: 这是 type1 构造函数:

template<typename T, dataType ST>
class type1: public sometype<T, ST>, public othertype<T, ST>, public anothertype
{
public:
    template <typename T1>
    type1(
        CSimSwcBase*           _plgInstance,
        const char*            _name,
        const T1&              _initialValue,
        const long             _version,
        const SimFunc_t        _eventFunc           = NULL,
        void*                  _eventFuncInstance   = NULL,
        const long             _size                = GetSize<T>::SIZE,
        const unsigned long    _portMode            = 0,
        const bool             _definedDefaultValue = false,
        void*                  _pDefaultValue       = NULL,
        const unsigned long    _defaultValueSize    = 0,
        const bool             _bBuffered           = false)
        : sometype(_plgInstance, _name, _initialValue, _size, _portMode, _eventFunc, _eventFuncInstance, _definedDefaultValue, _pDefaultValue, _defaultValueSize, _bBuffered)
        , othertype(dynamic_cast<sometype*>(this))
        , m_bUseSyncRef (false)
        , m_bGetDefaultValues(false)
        , m_bReportError(true)
        , m_errorCount(0)
        , m_maxError(100)
        , m_bDoOnlyStartupTest(false)
        , m_bStartupTestPassed(false)
        , m_bNotConnectedReported(false)
    {
        setupVersion(_version);
    }
}

你们有谁知道我该如何解决这个问题?

先谢谢了

标签: c++visual-studioc++11boost

解决方案


在没有足够清晰的情况下,需要在此处实际构建和复制:

auto data = boost::get<type1>(type[i]);

你可以简单地使用这样的参考来完成:

auto& data = boost::get<type1>(type[i]);

从而完全消除了构建的需要。


推荐阅读