为什么被认为是部分专业化

Why regarded as partial specialized

本文关键字:专业化 认为是部 为什么      更新时间:2023-10-16

有了下面的代码,我有点困惑为什么第二个foo被认为是部分专门化,而后者不是(IMO都不应该是部分)。

template <bool IS_TRUE>
int foo();
// Doesn't work!?
template <bool IS_TRUE>
int foo<IS_TRUE>() {
    return 0;
}
template <>
int foo<true>() {
    return 0;
}
int main() {
    return foo<true>();
}

在第二个foo上gcc抱怨:

错误:函数模板局部特化' foo '不是允许

谁能解释一下,我错过了什么细节

名称后带有模板参数的语法为部分专门化保留:

template<typename T> struct foo {};
template<typename T> struct foo<T *> {};

如果部分专门化不能专门化任何参数,你将得到如下错误:

template<typename T> struct foo {};
template<typename T> struct foo<T> {};
error: partial specialization 'foo<T>' does not specialize any template arguments

函数模板不允许部分特化(使用重载代替),所以编译器没有必要检查特化是否真的特化了任何模板参数;无论如何,这都是违法的。如果将函数的声明和定义分开,则应该省略声明和定义中的模板参数:

template<bool IS_TRUE> int foo();
template<bool IS_TRUE> int foo() { return 0; }
template<> int foo<true>() { return 0; }