专门用于引用类型的函数模板 [英] Specializing function template for reference types
问题描述
为什么是这个程式码的输出:
#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) ;
}
是
一般
一般
一般
General
General
General
第三个是因为该函数专用于 int&
The third one is surprizing because the function was specialized exactly for int&
编辑:我知道重载可能是一个合适的解决方案。
Edit : I know that overloading might be a proper solution. I just want to learn the logic behind it.
推荐答案
表达式 y
并且表达式 z
是 int
。表达式中出现的引用将不保留引用类型。相反,表达式的类型将是引用的类型,表达式是一个左值。
The type of both the expression y
and the expression z
is int
. A reference appearing in an expression won't keep reference type. Instead, the type of the expression will be the referenced type, with the expression being an lvalue.
因此,在这两种情况下, T
都被推导为 int
,因此根本不使用显式专用化。
So in both cases, T
is deduced to int
, and thus the explicit specialization is not used at all.
重要的是注意(除此之外,你应该真正使用重载,正如另一个人所说),是你的模板中有一个非引用的函数参数。在对参数类型进行 T
的任何推导之前,参数类型将从数组转换为指向其第一个元素的指针(对于函数,参数将被转换为函数指针)。因此,具有非引用函数参数的函数模板不允许准确的推断。
What's important to note (other than that you should really use overloading, as another guy said), is that you have a non-reference function parameter in your template. Before any deduction of T
against the argument type is done, the argument type will be converted from arrays to a pointer to their first element (for functions, arguments will be converted to function pointers). So a function template with a non-reference function parameter doesn't allow for accurate deduction anyway.
这篇关于专门用于引用类型的函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!