2016-09-07 31 views
4

我試用了boost msm lite這是一個非常好的狀態機實現。和往常一樣,我嘗試瞭解它是如何工作的,並找到了我無法理解的代碼片段。如何返回一個類型而不是一個對象是有效的,誤解代碼片段

這樣一句話:我不會張貼從提升這裏的整個文件,它是在這裏:https://github.com/boost-experimental/msm-lite/blob/master/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? 
} 

我(MIS)的認識這裏是,它會返回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}; 
     } 
}; 

下面的例子編譯罰款:

#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; 
} 
+2

這不能工作。 – SergeyA

+1

請告訴您用於編譯該代碼的內容。 –

+0

@ E_net4:我添加了我的示例代碼以重新編譯它。 – Klaus

回答

7
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,它不是一個模板變量(因此它必須在運算符函數中實例化)。

+1

哦,神祕解決了! – SergeyA

+2

對我而言,這是* evil * – NathanOliver

+0

我對自己印象深刻。之前被明確承認爲模板類的實例(例如'vector ')現在可以成爲實際對象。 –

相關問題