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

用于计算多个整数常量类型值之和的类型特性

编译时整数常量求和的类型特性

通过多个整数常量,我们可以定义一个名为Sum的类型特性,用于返回所有常量的总和。示例代码如下:

#include <type_traits>

template<typename...ARGS>
struct Sum : std::integral_constant<int,0> {};

template<typename T, typename...ARGS>
struct Sum<T,ARGS...> : std::integral_constant<int,T::value +  Sum<ARGS...>::value>  {};

struct One   : std::integral_constant<int,1> {};
struct Two   : std::integral_constant<int,2> {};
struct Three : std::integral_constant<int,3> {};

static_assert (Sum<One,Two,Three>::value == 6);

Q1:标准库中是否已提供此类类型特性?(我不想重复造轮子)

C++标准库并没有直接提供专门用于这类带::value的整数常量类型求和的Sum类型特性。不过你可以基于标准库的现有工具快速实现类似功能,不用自己从头写递归特化的模板。

Q2:能否不使用模板特化来定义该类型特性?

当然可以,不同C++版本都有对应的实现方式,完全不需要模板特化:

C++17及以上:用折叠表达式实现(最简洁)

结构体版本

#include <type_traits>

template<typename... Args>
struct Sum : std::integral_constant<int, (Args::value + ... + 0)> {};

struct One   : std::integral_constant<int,1> {};
struct Two   : std::integral_constant<int,2> {};
struct Three : std::integral_constant<int,3> {};

static_assert(Sum<One, Two, Three>::value == 6);

模板变量版本

#include <type_traits>

template<typename... Args>
inline constexpr int Sum_v = (Args::value + ... + 0);

struct One   : std::integral_constant<int,1> {};
struct Two   : std::integral_constant<int,2> {};
struct Three : std::integral_constant<int,3> {};

static_assert(Sum_v<One, Two, Three> == 6);

C++11/14:用constexpr函数配合参数包实现

#include <type_traits>

template<typename T>
constexpr int get_value() { return T::value; }

template<typename... Args>
constexpr int sum_constexpr() {
    return 0 + (... + get_value<Args>());
}

template<typename... Args>
struct Sum : std::integral_constant<int, sum_constexpr<Args...>()> {};

struct One   : std::integral_constant<int,1> {};
struct Two   : std::integral_constant<int,2> {};
struct Three : std::integral_constant<int,3> {};

static_assert(Sum<One, Two, Three>::value == 6);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:40:01