You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++11元编程:实现编译期判断所有布尔模板参数全为true

简化C++11中检查所有布尔模板参数全为true的实现

我需要在C++11里实现一个工具,用来判断传入的所有布尔模板参数是否全部为true。示例用法如下:

static_assert(all_true<true, true, true>::value); // 编译通过
static_assert(all_true<true, false, true>::value); // 编译失败

我自己写了一段实现代码:

template <bool b>
struct bool_type : std::false_type {};

template <>
struct bool_type<true> : std::true_type {};

template <bool val, bool... vals>
struct all_true : bool_type<bool_type<val>::value && all_true<vals...>::value> {};

template <>
struct all_true<true> : bool_type<true> {};

template <>
struct all_true<false> : bool_type<false> {};

可以看到这段代码需要额外定义bool_type结构体(含特化版本),还要对all_true做特化。有没有办法简化这段代码?

编辑
正如@user17732522指出的,可以用std::integral_constant来优化,优化后的代码如下:

template <bool val, bool... vals>
struct all_true : std::integral_constant<bool, val && all_true<vals...>::value> {};

template <>
struct all_true<true> : std::integral_constant<bool, true> {};

template <>
struct all_true<false> : std::integral_constant<bool, false> {};

内容的提问来源于stack exchange,提问作者NiklasMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:13:18