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

为何模板能接受不符合概念约束的模板实参?

模板模板参数概念约束的编译器行为差异

先看这段C++代码:

template <typename T>
concept C1 = sizeof(T) != sizeof(int);

template <template <C1 T> class X>
struct S4
{
    X<int> x;
};

template <typename T>
class Test
{
  public:
    T t;
};

int main()
{
    S4<Test> s1;  
    return 0;
}

代码逻辑与预期

S4定义时要求接收的模板模板实参X,其类型参数必须满足概念C1(即类型大小不等于int)。但代码中用无任何约束的Test模板实例化S4,同时在S4内部还尝试用int去实例化X——这明显违反了C1的约束,按道理应该编译报错。

不同编译器的表现

  • GCC和Clang可以无错误编译这段代码
  • MSVC会抛出错误:
    error C3201: the template parameter list for class template 'Test' does not match the template parameter list for template parameter 'X'x64 msvc v19.40 VS17.10 #Executor 1
    

这个报错符合预期:因为X的参数受C1约束,而Test的模板参数没有任何约束,二者的模板参数列表不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:32:09