[英]Is there a reason to use std::conjunction/std::disjunction instead of a fold expression over "&&"/"||"?
是否有任何特定情況您無法正確使用std::conjunction
/ std::disjunction
並且不使用更多“基本”(即語言功能而不是庫功能)折疊表達式而不是&&
/ ||
?
例子:
// func is enabled if all Ts... have the same type
template<typename T, typename... Ts>
std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...> >
func(T, Ts...) {
// TODO something to show
}
對比
// func is enabled if all Ts... have the same type
template<typename T, typename... Ts>
std::enable_if_t<(std::is_same<T, Ts> &&...)>
func(T, Ts...) {
// TODO something to show
}
使用折疊表達式的版本更簡潔,通常更易讀(盡管對此意見可能有所不同)。 所以我不明白為什么它與折疊表達式一起添加到庫中。
std::conjunction
短路::value
實例化,而折疊表達式則不然。 這意味着,給定:
template <typename T>
struct valid_except_void : std::false_type { };
template <>
struct valid_except_void<void> { };
以下將編譯:
template <typename... Ts>
constexpr auto test = std::conjunction_v<valid_except_void<Ts>...>;
constexpr auto inst = test<int, void>;
但以下不會:
template <typename... Ts>
constexpr auto test = (valid_except_void<Ts>::value && ...);
constexpr auto inst = test<int, void>;
從cppreference :
連接是短路的:如果有一個帶有
bool(Bi::value) == false
的模板類型參數Bi
,那么實例化conjunction<B1, ..., BN>::value
不需要實例化Bj::value
j > i
Bj::value
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.