如何返回一个类型而不是一个对象是有效的,误解了一个代码片段

Kla*_*aus 4 c++ boost c++14

我尝试了boost msm lite,这是一个非常好的状态机实现.一如既往,我试着理解它是如何工作的,并找到了一个我无法理解的代码片段.

作为一个评论:我不会在这里发布来自boost的整个文件,它在这里:https://github.com/boost-experimental/msm-lite/blob/master/include/boost/msm-lite.hpp

测试代码仅用于理解窗帘背后的事物:

 auto x2 = "test"_t;  //compiles fine!
Run Code Online (Sandbox Code Playgroud)

这应该转到这个代码片段:

 template <class T, T... Chrs>
 auto operator""_t() BOOST_MSM_LITE_NOEXCEPT {
      return event<aux::string<Chrs...>>;       // ??? How this can work?
 }
Run Code Online (Sandbox Code Playgroud)

我(错误)的理解是,它将返回type而不是类型的实例?但它编译......为什么?

event 定义为:

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}; 
        }   
};
Run Code Online (Sandbox Code Playgroud)

以下示例编译正常:

#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;
}
Run Code Online (Sandbox Code Playgroud)

E_n*_*ate 7

template <class T, T... Chrs>
auto operator""_t() BOOST_MSM_LITE_NOEXCEPT {
    return event<aux::string<Chrs...>>;       // ??? How this can work?
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理是因为此运算符不返回类型,而是返回模板变量的实例,该实例event第1536行中定义:

template <class TEvent>
detail::event<TEvent> event{};
Run Code Online (Sandbox Code Playgroud)

模板变量仅在C++ 14中引入,这可能是您更难找到和理解的原因.还要注意_s运算符依赖于state,它不是模板变量(因此必须在运算符函数中实例化它).

  • 对我来说,这是邪恶的* (3认同)