4

我目前正在为游戏编写一些代码,其中一部分涉及创建迄今为止在游戏中发生的动作的历史记录。此历史记录存储在state_pair_t' 对动作 ( action_t's) 的向量中,并在执行动作后指向结果游戏状态的指针。现在我有一个函数,它从最近的时间点开始查看历史并向后迭代,直到找到某种类型的动作,然后返回对该动作的引用。no_action现在我们决定,如果没有找到任何操作,使用 boost optional 来返回 a并用于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吗?甚至可能吗?

4

1 回答 1

2

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

您的代码的问题是您试图将非 const 可选引用绑定到 const 左值;如果你改成boost::optional< action_t& >boost::optional< const action_t& >应该编译得很好。

于 2013-04-05T07:29:04.570 回答