C++模板元一生之敌之:std::disconjunction

std::disconjunction

disconjunction是上篇介绍的conjunction的同胞兄弟,模板参数包中至少有一个为ture时,其value为true,相当于对一系列类型特性(type traits)做逻辑或(Or)

std::disjunction<Bs...>::value // is true if at least one of Bs... is true, false otherwise

先看如下应用实例,这个例子本身看起来也比较恶心,整个人有点不好了,可自行食用:

#include <cstdint>
#include <string>
#include <type_traits>

// values_equal<a, b, T>::value is true if and only if a == b.
template<auto V1, decltype(V1) V2, typename T>
struct values_equal : std::bool_constant<V1 == V2>
{
using type = T;
};

// default_type<T>::value is always true
template<typename T>
struct default_type : std::true_type
{
using type = T;
};

// Now we can use disjunction like a switch statement:
template<int I>
using int_of_size = typename std::disjunction< //
values_equal<I, 1, std::int8_t>,           //
values_equal<I, 2, std::int16_t>,          //
values_equal<I, 4, std::int32_t>,          //
values_equal<I, 8, std::int64_t>,          //
default_type<void>                         // must be last!
>::type;

static_assert(sizeof(int_of_size<1>) == 1);
static_assert(sizeof(int_of_size<2>) == 2);
static_assert(sizeof(int_of_size<4>) == 4);
static_assert(sizeof(int_of_size<8>) == 8);
static_assert(std::is_same_v<int_of_size<13>, void>);

disconjunction代码实现

有了上篇conjunction的介绍,disconjunction的实现代码就一目了然了

template<class...> struct disjunction : std::false_type {};

template<class B1> struct disjunction<B1> : B1 {};

template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>>  {};

换一种思路,至少一个为真的逆否命题为:非全部为假

全部为假的条件为全部非真,那么借助上篇讲的conjunction,我们可以得到如下的实现:

template <bool B>
using bool_constant = std::integral_constant<bool, B>; 

template<bool... Bs>
struct disjunction : bool_constant<!conjunction<!Bs...>::value>{};
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值