Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - Specializing function template for reference types

Why is the output of this 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) ; 
}  

is

General
General
General

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

So in both cases, T is deduced to int, and thus the explicit specialization is not used at all.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...