c++ - 变量模板的部分特化

标签 c++ templates language-lawyer partial-specialization variable-templates

我知道我可以部分特化类模板,我知道我不能部分特化函数模板。

variable templates呢? ?我找不到关于它们是否可以部分专门化的文档。

最佳答案

是的,根据 [temp.arg.template]/2 :

Any partial specializations associated with the primary class template or primary variable template are considered when a specialization based on the template template-parameter is instantiated. ...

然后到 [temp.expl.spec]/7 :

... the placement of partial specialization declarations of class templates, variable templates, member class templates of non-template classes, static data member templates of non-template classes, member class templates of class templates, etc. ...

[constraints.namespace.std]/3中也提到了:

The behavior of a C++ program is undefined if it declares an explicit or partial specialization of any standard library variable template, except where explicitly permitted by the specification of that variable template.


更不用说所有主要编译器(Clang、GCC 和 MSVC)都没有问题:

template <int x, int y>
constexpr int foo = -1;

template <>
constexpr float foo<1, 0> = 1.0;

template <int x>
constexpr double foo<1, x> = 1.1;

int main()
{
    static_assert(foo<0, 0> == -1, "");
    static_assert(foo<0, 1> == -1, "");
    static_assert(foo<1, 0> == 1.0, "");
    static_assert(foo<1, 1> == 1.1, "");
}

https://godbolt.org/z/R1c1zo

关于c++ - 变量模板的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52115814/

相关文章:

c++ - "Enlarging"一个二维数组 (m,n)

c++ - 如何从派生类访问派生基成员?(在 C++ 中)

java - FreeMarker:检查 map 值是否为空

c++ - 在编写包装现有函数并检查错误的模板函数时,如何使用完美转发?

c++ - 在 int 数组的情况下可以使用 new 表达式 "overflow"吗?

c++ - 为什么 std::map 有一个名为 count 的成员函数?

c++ - QML 和 C++ 图像互操作性

c++ - MathGL BoxPlot 的数据格式

c++ - 来自空括号的不明确复制分配的编译器差异

python - 访问文字上的属性适用于所有类型,但不适用于 `int` ;为什么?