template <class Handler>
struct ContextType {
typedef typename std::conditional<
Handler::dir == HandlerDir::BOTH,
ContextImpl<Handler>,
typename std::conditional<
Handler::dir == HandlerDir::IN,
InboundContextImpl<Handler>,
OutboundContextImpl<Handler>
>::type>::type
type;
};
上面的代碼乍一看仿佛很難,但是仔細研究一下也不過如此哈,首先我們要知道 std::conditional 是什麼意思,該函數的官方解釋為根據判斷條件定義type 為何類型,如果判斷條件為true,則type定義為第二個參數類型,否則為第三個參數類型。
延伸到ContextType 上來解釋就是如果模闆Handler的dir是BOTH,則參數類型為 ContextImpl<Handler> ,否則調用 typename std::conditional<
Handler::dir == HandlerDir::IN,
InboundContextImpl<Handler>,
OutboundContextImpl<Handler>
>::type 和上面分析的流程一樣,到此 ContextType 的type 就有三種可能,如果dir 為IN 則為 InboundContextImpl<Handler> 如果為OUT 則為OutboundContextImpl<Handler>,如果為BOTH 則為ContextImpl<Handler>