gpt4 book ai didi

c++ - boost::optional reference with boost::variant 类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:26 27 4
gpt4 key购买 nike

我目前正在为游戏编写一些代码,其中一部分涉及创建游戏中迄今为止发生的操作的历史记录。此历史记录存储在一个 vector 中,该 vector 由 state_pair_t 的 Action 对(action_t)和一个 Action 完成后指向结果游戏状态的指针组成。现在我有一些函数,它从最近的时间点开始查看历史记录并向后迭代,直到找到某种类型的 Action ,然后返回对该 Action 的引用。现在我们决定,如果没有找到任何 Action ,使用 boost optional 返回一个 no_action 并使用 boost::optional 来处理这些函数可能是一个很好的设计举措应该返回一个值但可能没有要返回的值。当我实际尝试实现它时,我遇到了一个我不明白的错误:

typedef boost::variant<
A,
B,
B
> action_t;

typedef boost::optional< action_t& > opt_action_ref_t;

const opt_action_ref_t no_action = opt_action_ref_t();

/*! A state pair is the combination of a particular action and the resulting game state */
typedef std::pair< const action_t, game_state_ptr > state_pair_t;

opt_action_ref_t get_last_non_A_action() const{
std::vector< state_pair_t >::const_reverse_iterator rcit;
for(rcit = m_states.rbegin(); m_states.rend() != rcit ; ++rcit){
if(!(is_action_type< A >(rcit->first))){
return rcit->first; \\error at compile time
}
}

return no_action;
}

现在这给出了一个编译错误:

Error error C2664: 'boost::optional<T>::optional(boost::none_t)' : cannot convert parameter 1 from 'const action_t' to 'boost::none_t'

现在,如果我将其稍微更改为:

    if(!(is_action_type< A >(rcit->first))){
return boost::optional<action_t>(rcit->first);
}

我收到另一个错误:

error C2664: 'boost::optional<T>::optional(boost::none_t)' : cannot convert parameter 1 from 'boost::optional<T>' to 'boost::none_t'

我不确定这些错误中的任何一个试图在这里告诉我什么。我在这里尝试使用 boost::optional 做的不是一个好主意吗?有可能吗?

最佳答案

可选引用本身就是一个好主意; recent paper n3527 中特别提到了它们,旨在作为 C++14 中的库组件进行标准化。它们在 Boost.Optional 中受支持.

您的代码的问题是您试图将一个非常量可选引用绑定(bind)到一个 const 左值;如果你改变 boost::optional< action_t& >boost::optional< const action_t& >它应该可以正常编译。

关于c++ - boost::optional reference with boost::variant 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com