c++ - 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);
}
}
你们有谁知道我该如何解决这个问题?
先谢谢了
解决方案
在没有足够清晰的情况下,需要在此处实际构建和复制:
auto data = boost::get<type1>(type[i]);
你可以简单地使用这样的参考来完成:
auto& data = boost::get<type1>(type[i]);
从而完全消除了构建的需要。
推荐阅读
- html - 时间验证(不时)
- laravel - 调用关系返回错误“最大执行时间为 60 秒”
- deep-learning - PyTorch 在第一个可用的 GPU (cuda:0) 上分配更多内存
- kotlin - 有没有办法让 NavigationView 占用更少的代码(Kotlin)
- nginx - nginx 代理服务器上的连接问题(可能是 socket.io 问题)
- java - 在 ANTLR4 词法分析器中,如何定义用例后面的负面外观
- azure - 在 JWT 令牌中包含 AAD 组名称
- javascript - 如何使用 jest 访问导出函数的对象以进行单元测试
- spring-boot - 是否可以在 Spring Boot 中设置没有注释的 http 路由?
- linux - 我想在我的 linux 服务器 (.sh) 中设置 cron 作业。但我有一个错误