有没有理由使用 std::conjunction/std::d isjunction 而不是 "&&" / "||" 上的折叠表达式?
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
}
vs
// 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>;
godbolt.org上的实时示例
来自cppreference:
连词是短路的:如果有一个模板类型参数
。Bi
bool(Bi::value) == false
,则实例化conjunction<B1, ..., BN>::value
不需要Bj::value
的CC_10实例化。
相关文章:
- 将fold表达式与std::一起用于两个元组
- 将 lambda 表达式传递给 std::function in C++
- 在 lambda 表达式中使用 std::atomic
- C++ IDE 不会推断/自动完成对模板类中的 std::array 下标表达式的成员访问
- std::cout 在打印变量与函数表达式时的行为不同
- 针对 std::function 的 lambda 表达式和模板推导:为什么会这样?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 在c++std::函数的上下文中无效使用void表达式
- 我可以std::在fold表达式中转发参数吗
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 为什么一个表达式中的 std::string 连接给出的结果与逐个字符不同的结果?
- 计算表达式字符串由 std::map 中的键组成
- 如何使 std::正则表达式匹配 Utf8
- C++11 (MSVS2012) 正则表达式在多行 std::string 中查找文件名
- std::正则表达式捕获组语法错误
- std::d eclval 和未计算的表达式
- 如何修复此错误:二进制表达式的操作数无效("std::vector<double>"和"double")?
- std::正则表达式转义"+"符号
- whats type*在表达式std :: enable_if中
- 使用 STD 正则表达式标记逗号分隔的列表