变量模板的部分特化
Partial Specialization of Variable Templates
我知道我可以部分特化 class 模板,我知道我不能部分特化函数模板。
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. ...
... 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, "");
}
我知道我可以部分特化 class 模板,我知道我不能部分特化函数模板。
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. ...
... 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, "");
}