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

针对const与非const指针的类模板偏特化问题咨询

指针类型非类型模板参数的偏特化问题

我尝试实现一个带有指针类型非类型模板参数的类模板,为const指针和非const指针分别提供偏特化版本。


第一种尝试方案

我先写了如下代码:

template <const int*>
struct A {};

template <int* p>
struct A<p>;

int v;
A<&v> a;
  • Clang和GCC可以编译这段代码,但尽管&v的类型是int*,A<&v>却会匹配带const指针的主模板。
  • MSVC直接报错:
error C2753: 'A<p>': partial specialization cannot match argument list for primary template

请问该偏特化是否符合标准?如果是合法的,该如何实例化使用int*版本的A?


第二种尝试方案

我改用auto非类型模板参数声明主模板,再分别特化非const和const指针版本:

template <auto>
struct A;

template <int* p>
struct A<p> {};

template <const int* p>
struct A<p>;

int v;
A<&v> a;
  • GCC下这段代码可以正常工作,A<&v>会匹配int*的偏特化。
  • Clang和MSVC均报歧义错误:
// Clang错误
error: ambiguous partial specializations of 'A<&v>'

// MSVC错误
error C2752: 'A<&v>': more than one partial specialization matches the template argument list

既然按照模板特化的规则,template <int* p>应该比template <const int* p>更特化,那到底哪种方案才是符合C++标准的正确写法?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:22:21