[英]C++ Variadic template AND and OR
你能用C ++ 11可變參數模板來完成/* ??? */
/* ??? */
in:
template<bool...v> struct var_and { static bool constexpr value = /* ??? */; };
這樣var_and<v...>::value
在編譯時提供了&&
over boolean pack v
?
你可以對struct var_or<v...>
為||
做同樣的struct var_or<v...>
?
你能用短路評估(兩種情況下)嗎?
編輯 :對已接受答案的更新添加了C ++ 17 折疊表達式啟用
template<bool... v> constexpr bool var_and = (v && ...);
template<bool... v> constexpr bool var_or = (v || ...);
看來,對於基於參數包的方法,只能進行限制類型的“短路評估”:實例化var_or<true,foo(),bar()>
只調用||
曾經,它也稱為foo
和bar
。
您不希望value
成為typedef。
template<bool head, bool... tail>
struct var_and {
static constexpr bool value = head && var_and<tail...>::value;
};
template<bool b> struct var_and<b> {
static constexpr bool value = b;
};
顯然,對於||
也可以這樣做 。
短路評估無關緊要,因為這只涉及不會產生任何副作用的常數表達式。
這是另一種方法,一旦發現錯誤值就會停止遞歸生成類型,模擬一種短路:
template<bool head, bool... tail>
struct var_and { static constexpr bool value = false; };
template<bool... tail> struct var_and<true,tail...> {
static constexpr bool value = var_and<tail...>::value;
};
template<> struct var_and<true> {
static constexpr bool value = true;
};
更新C ++ 17:使用fold表達式可以簡化這一過程。
template<bool...v> struct var_and {
static constexpr bool value = (v && ...);
};
或者使用模板變量作為enobayram建議:
template<bool... b> constexpr bool var_and = (b && ...);
我只需要類似的東西,但我有使用C ++ 14的奢侈,所以我最終得到了以下內容,這可能比接受的答案更快(編譯):
template <size_t N>
constexpr bool and_all(const bool (&bs) [N]) {
for(bool b: bs) if(!b) return false;
return true;
}
現在,這是constexpr,因此它可以在編譯時上下文和運行時使用。 因此,我們可以在some_struct<and_all({true, false, arg_pack...})>
等上下文中使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.