【发布时间】:2016-08-25 23:14:15
【问题描述】:
考虑以下情况:
#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 的特化)除了编码方便之外,它有什么特殊用途吗?
【问题讨论】:
标签: c++ template-specialization