【发布时间】:2011-01-13 07:03:28
【问题描述】:
为什么这个code的输出是:
#include <iostream>
template<typename T> void f(T param)
{
std::cout << "General" << std::endl ;
}
template<> void f(int& param)
{
std::cout << "int&" << std::endl ;
}
int main()
{
float x ; f (x) ;
int y ; f (y) ;
int& z = y ; f (z) ;
}
是
一般
一般
一般
第三个令人惊讶,因为该函数专门针对int&
编辑:我知道重载可能是一个合适的解决方案。我只是想学习它背后的逻辑。
【问题讨论】:
-
也许是因为 const int& 比 int& 更受欢迎?
-
@Septagram: const int& ?
-
我不知道它是否有帮助,但是如果您将模板更改为接受
T &,那么f(y)和f(z)都调用int &版本。 -
@Daniel Gallagher:那么您遇到了
f(2);的编译器错误。f(y)的输出也是int&。 -
最好的办法是使用重载
void f(int& param)gotw.ca/publications/mill17.htm
标签: c++ templates specialization template-specialization reference-type