我尝试了 boost msm lite,这是一个非常好的状态机实现。一如既往,我试图了解它是如何工作的,但发现了一个我无法理解的代码片段。
请注意:我不会在这里发布来自 boost 的整个文件,它在这里:https://github.com/boost-experimental/sml/blob/f636c05cb1a483e5131348d59d6151453ca3f9f2/include/boost/msm-lite.hpp
测试代码仅供了解幕后情况:
auto x2 = "test"_t; //compiles fine!
那应该转到这个代码片段:
template <class T, T... Chrs>
auto operator""_t() BOOST_MSM_LITE_NOEXCEPT {
return event<aux::string<Chrs...>>; // ??? How this can work?
}
我的(错误)理解是,它将返回 type
而不是该类型的实例?但它编译...为什么?
事件
定义为:
template <class>
struct event {
template <class T, BOOST_MSM_LITE_REQUIRES(concepts::callable<bool, T>::value)>
auto operator[](const T &t) const BOOST_MSM_LITE_NOEXCEPT {
return transition_eg<event, T>{*this, t};
} template <class T, BOOST_MSM_LITE_REQUIRES(concepts::callable<void, T>::value)>
auto operator/(const T &t) const BOOST_MSM_LITE_NOEXCEPT {
return transition_ea<event, T>{*this, t};
}
};
以下示例编译良好:
#include <cassert>
#include <iostream>
#include "boost/msm-lite.hpp"
namespace msm = boost::msm::lite;
int main()
{
using namespace msm;
auto x1 = "idle"_s;
auto x2 = "test"_t;
}
最佳答案
template <class T, T... Chrs>
auto operator""_t() BOOST_MSM_LITE_NOEXCEPT {
return event<aux::string<Chrs...>>; // ??? How this can work?
}
之所以有效,是因为此运算符返回的不是类型,而是模板变量 event
的实例,它在 line 1536 中定义。 :
template <class TEvent>
detail::event<TEvent> event{};
模板变量仅在 C++14 中引入,这可能是您更难找到和理解的原因。另请注意,_s 运算符依赖于 state
。 ,它不是模板变量(因此必须在运算符函数中对其进行实例化)。
关于c++ - 返回类型而不是对象如何有效,误解了代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39373008/