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

如何在C++中实现可检查任意模板类型相等性的concept?

实现通用的类型相等检查Concept

当然可以,C++20支持模板化的concept,你只需要定义一个带两个模板参数的concept,第一个是期望的类型,第二个是待验证的类型,就能实现你想要的通用类型相等检查:

#include <type_traits>
#include <string>

template<typename Expected, typename T>
concept ValidType = std::is_same_v<T, Expected>;

// 使用示例:只接受int类型的参数包
template<ValidType<int>... Ints>
void passInts(Ints... ints) {}

// 使用示例:只接受std::string类型的参数包
template<ValidType<std::string>... Strings>
void passStrings(Strings... strings) {}

原理说明

这个ValidType concept通过两个模板参数实现通用约束:

  • 第一个模板参数Expected是你期望匹配的目标类型(比如int或std::string)
  • 第二个模板参数T是待检查的实际类型
  • 利用std::is_same_v<T, Expected>判断两者是否完全一致

当你写ValidType<int>... Ints时,编译器会对参数包中的每个Ints类型,自动推导并检查ValidType<int, Ints_i>是否成立,只有所有参数类型都匹配int,模板才会被选中。

对比conjunction写法

你提到的conjunction(或折叠表达式)写法是这样的:

template<typename... Ints>
requires (std::is_same_v<Ints, int> && ...)
void passInts(Ints... ints) {}

而用ValidType的写法更具复用性——只需定义一次concept,就能用任意期望类型来约束不同的模板,代码更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:55:23