考虑以下情况:如何在函数模板的显式特化中推导出模板参数?
#include <iostream>
template <class T> void f(T) { std::cout << "#1\n"; } // #1
template <> void f(const int) { std::cout << "#2\n"; } // #2
int main() {
f<const int>(1); // call #1
f<int>(1); // call #2
return 0;
}
似乎#2是f<int>(const int)
,而不是f<const int>(const int)
。这里发生了什么?我的第一个想法是顶级const
在函数类型转换中被丢弃,所以#2的类型是void(int)
,这导致了f<int>(const int)
的专门化。但我不确定这一点。
为什么C++允许这样的语法?我的意思是,既然我们不能部分专门化函数模板,如果我们想明确地专门化一个模板参数值,我们就会知道模板参数的值。那么为什么C++不只是强制程序员在专门化模板函数时明确提供模板参数值呢? (即我们必须在template <> void f<int>(const int) { }
或template <> void f<int const>(const int) { }
中编写#1专业化)除了编码方便之外,它有特殊的用法吗?