[英]Calling overloading template function by func(1) and func<int>(1) leads to difference result
I have two template functions:我有两个模板函数:
template <typename T>
void func(T a)
{ std::cout << "func(T a)" << std::endl; }
template <typename T>
void func(int a)
{ std::cout << "func(int a)" << std::endl; }
And calling func
which different method will lead to different result:而调用
func
不同的方法会导致不同的结果:
func(1); // call func(T a)
func<int>(1); // call func(int a)
Here is the demo .这是演示。 I originally thought that
func(1)
and func<int>(1)
are identical, but it seems that I was wrong.我原本认为
func(1)
和func<int>(1)
是相同的,但看来我错了。 Does compiler treat func(1)
and func<int>(1)
differently?编译器是否以不同方式对待
func(1)
和func<int>(1)
? Thanks for any help!谢谢你的帮助!
The call func<int>(1);
调用
func<int>(1);
chooses the second overload because it is more specialized.选择第二个重载,因为它更专业。
The call func(1);
调用
func(1);
can't choose the second overload, because the second overload has a template parameter T
which is neither given a template argument explicitly (as in func<int>(1);
), nor can be deduced from the function parameter/argument pair (as T
in the first overload can from the argument 1
to the T a
parameter).不能选择第二个重载,因为第二个重载有一个模板参数
T
,它既没有明确地给出模板参数(如func<int>(1);
),也不能从 function 参数/参数对(因为第一个重载中的T
可以从参数1
到T a
参数)。 If a template argument can't be deduced and isn't explicitly given, then the overload is non-viable in overload resolution.如果无法推导模板参数并且未明确给出,则重载在重载决策中是不可行的。 The only remaining overload is the first one, which is then chosen.
唯一剩下的过载是第一个,然后选择它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.