变量模板的部分专业化

时间:2018-08-31 12:47:45

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

我知道我可以部分专门化类模板,并且我不能部分指定函数模板。

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

1 个答案:

答案 0 :(得分:4)

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

  实例化基于模板template-parameter的专业化时,将考虑与主要类模板或主要变量模板相关的任何部分专业化。 ...

并转到[temp.expl.spec]/7

  

... 类模板的部分专业化声明,变量模板,非模板类的成员类模板,非模板的静态数据成员模板的放置类,类模板的成员类模板等。

它在[constraints.namespace.std]/3中也提到过:

  

如果C ++程序声明了任何标准库变量模板的显式或部分专业化,则该C ++程序的行为未定义,除非该变量的规范明确允许模板。


更不用说所有主要的编译器(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