Specializing function template for reference types

后端 未结 3 1771
南旧
南旧 2020-12-19 00:46

Why is the output of this code :

#include   
template void f(T param) 
{ 
   std::cout << \"General\" << std::e         


        
3条回答
  •  粉色の甜心
    2020-12-19 01:13

    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.

提交回复
热议问题