gpt4 book ai didi

c++ - 是否有理由使用 std::conjunction/std::disjunction 而不是 "&&"/"||"上的折叠表达式?

转载 作者:IT老高 更新时间:2023-10-28 21:56:47 24 4
gpt4 key购买 nike

是否存在您无法正确使用 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>;

live example on godbolt.org


来自 cppreference :

Conjunction is short-circuiting: if there is a template type argument Bi with bool(Bi::value) == false, then instantiating conjunction<B1, ..., BN>::value does not require the instantiation of Bj::value for j > i.

关于c++ - 是否有理由使用 std::conjunction/std::disjunction 而不是 "&&"/"||"上的折叠表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55161235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com