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

如何实现支持任意数量类型的is_same_many模板结构体?

实现检查任意多个类型是否全部相同的模板结构体

C++的type_traits库提供了is_same工具用来检查两个类型是否一致,现在我们要实现一个模板结构体is_same_many,支持检查任意长度的类型列表是否全部相同——当所有传入的类型都一致时,其成员value为true,否则为false。

需要实现的模板声明如下:

template <class... U>
struct is_same_many;

实现方案

我们可以通过模板特化结合C++标准库工具来完成这个功能,下面提供两种常用实现方式:

方式1:递归展开参数包(兼容C++11及以上)

通过递归逐个比较第一个类型与后续所有类型是否一致:

#include <type_traits>

// 空参数包特化:默认视为所有类型相同
template <>
struct is_same_many<> : std::true_type {};

// 单个类型特化:只有一个类型时必然满足条件
template <class T>
struct is_same_many<T> : std::true_type {};

// 多个类型的通用处理:递归比较第一个类型与第二个类型,同时检查剩余列表
template <class T, class U, class... Rest>
struct is_same_many<T, U, Rest...> : 
    std::conjunction<std::is_same<T, U>, is_same_many<T, Rest...>> {};

方式2:折叠表达式简化(C++17及以上)

利用C++17的折叠表达式可以避免递归,写出更简洁的实现:

#include <type_traits>

// 空参数包特化
template <>
struct is_same_many<> : std::true_type {};

// 多类型处理:用折叠表达式一次性比较所有类型与第一个类型是否一致
template <class T, class... Rest>
struct is_same_many<T, Rest...> : 
    std::bool_constant<(std::is_same_v<T, Rest> && ...)> {};

使用示例

int main() {
    // 验证全部相同的情况
    static_assert(is_same_many<int, int, int>::value, "All int types should be identical");
    // 验证存在不同类型的情况
    static_assert(!is_same_many<int, float, int>::value, "Mixed types should not be identical");
    // 验证单个类型的情况
    static_assert(is_same_many<char>::value, "Single type is always identical");
    // 验证空参数包的情况
    static_assert(is_same_many<>::value, "Empty type pack is considered identical");
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:05:21