没有模板化参数的函数模板特化

Suk*_*lay 2 c++

让我们看一个模板函数,它接受void参数并返回void:

template<class T>
void f() {
    cout << "template" << endl;
}
Run Code Online (Sandbox Code Playgroud)

后来我们专门研究这个功能:

template<>
void f<int> () {
    cout << "int" << endl;
}
template<>
void f<double> () {
    cout << "double" << endl;
}

int main() {
    f<int> ();
    f<double> ();
}
Run Code Online (Sandbox Code Playgroud)

问题是为什么这个编译?我们有三个具有相同签名的功能: void(void),我预计它应该打破多个声明?

Tar*_*ama 6

这是因为您明确说明要使用哪个函数.由于模板参数的不同,f<int>()无法映射到f<double>(); 即这是一个完全明确的呼吁.