[英]c++ function template specify second template parameter type
just started learning template programming, I have the following code, 刚开始学习模板编程,我有以下代码,
template<typename T, typename U>
void add(T x, U y)
{
cout<< x + y <<endl;
}
I can call this by, 我可以称之为,
add(1, 2);
add<int, int>(1, 2);
add<int>(1, 2.0);
In the third case, I believe that means I specified [T=int]
, and compiler will deduce [U=double]
在第三种情况下,我认为这意味着我指定[T=int]
,编译器将推导出[U=double]
My question is how can I specify the second parameter type explicitly? 我的问题是如何明确指定第二个参数类型?
What about add(1,(int)2.0);
那么add(1,(int)2.0);
. 。
In theory according to template argument deduction rules, this causes the second template parameter to be deduced as int
.So this is stricktly equivalent to this hypothetical syntax add<U=int>(1,2.0);
理论上,根据模板参数推导规则,这会导致第二个模板参数推导为int
。因此,这与假设的语法add<U=int>(1,2.0);
严格等价 add<U=int>(1,2.0);
So this is the way to specify the second template argument! 所以这是指定第二个模板参数的方法!
It is impossible to find an equivalent syntax if the second template argument is non-deductible: 如果第二个模板参数不可抵免,则无法找到等效语法:
template<class T>
struct t_{
using type = T;
};
template<class T,class U>
auto add(T, typename t_<U>::type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.