我正在阅读有关模板函数的内容,遇到了以下问题:
#include <iostream>
void f(int) {
std::cout << "f(int)\n";
}
template<typename T>
void g(T val) {
std::cout << typeid(val).name() << " ";
f(val);
}
void f(double) {
std::cout << "f(double)\n";
}
template void g<double>(double);
int main() {
f(1.0); // f(double)
f(1); // f(int)
g(1.0); // d f(int), this is surprising
g(1); // i f(int)
}
如果我不写
template void g<double>(double);
,结果是一样的。我认为
g<double>
应该在f(double)
之后实例化,因此在g
中对f
的调用应该调用f(double)
。令人惊讶的是,在g<double>
中仍然调用f(int)
。有人能帮我理解这个问题吗?
阅读答案后,我明白了我的困惑所在。
这是一个更新的例子,除了我添加了一个针对
g<double>
的专门化外,大部分内容都没有改变:#include <iostream>
void f(int){cout << "f(int)" << endl;}
template<typename T>
void g(T val)
{
cout << typeid(val).name() << " ";
f(val);
}
void f(double){cout << "f(double)" << endl;}
//Now use user specialization to replace
//template void g<double>(double);
template<>
void g<double>(double val)
{
cout << typeid(val).name() << " ";
f(val);
}
int main() {
f(1.0); // f(double)
f(1); // f(int)
g(1.0); // now d f(double)
g(1); // i f(int)
}
有了用户专业化,g(1.0)
的行为与我预期的一样。
编译器是否不会在同一位置(或甚至在main()
之后,如第4版The C++ Programming Language的26.3.3节中所述)自动进行g<double>
的实例化?
g(1)
对我来说返回的是i f(int)
。而你写的是d f(double)
,这是打字错误吗?请确认。 - HTNW