【问题标题】:Partial Specialization of Variable Templates变量模板的部分专业化
【发布时间】:2019-02-06 12:10:59
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    在实例化基于模板模板参数的特化时,会考虑与主类模板或主变量模板关联的任何部分特化。 ...

    还有[temp.expl.spec]/7

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

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

    如果 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

    【讨论】:

    • Welp,看来我只是把尖括号放在了错误的位置。谢谢,我会尽快接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多