型別選擇之 Conditional 和 Select
阿新 • • 發佈:2020-06-30
Conditional:在兩種型別中進行選擇的方法。 Select:在多種型別中進行選擇的方法。 區別: ?: 是在多個值中進行選擇。而Conditional和Select是用來選擇型別的。 關於conditional: conditional模板是標準庫的一部分(定義在<type_traits>中)。 其實現為: template<bool C, typename T, typename F> //通用模板 struct conditional{ using type = T; }; template<typename T, typename F> //false的特例化版本 struct conditional<false,T,F>{ using type = F; }; 例如: typename std::conditional<(std::is_polymorphic<T>::value),X,Y>::type z; 為了改進語法,可以也引入一個別名: template<bool B, typename T, typename F> using Conditional = typename std::conditional<B,T,F>::type; 同時新增一個函式: template<typename T> constexpr bool Is_polymorphic() { return std::is_polymorphic<T>::value; } 基於上面的定義,可以改寫此程式碼為: Conditional<(Is_polymorphic<T>()),X,Y> z; 關於select: template<unsigned N, typename... Cases> //一般情況;不會被例項化 struct select; template<unsigned N, typename T, typename... Cases> structselect<N,T,Cases...> :select<N-1,Cases...>{ }; template<typename T, typename... Cases> //最終情況:N==0 struct select<0,T,Cases...>{ using type = T; }; template<unsigned N, typename... Cases> using Select = typename select<N,Cases...>::type;