我有这样的模板:将参数传递给模板
template<class a>
a multiply(a x, a y){
return x*y;
}
我如何可以通过不同类型的参数? (int和float例如)
我有这样的模板:将参数传递给模板
template<class a>
a multiply(a x, a y){
return x*y;
}
我如何可以通过不同类型的参数? (int和float例如)
这取决于你想要达到的目标。您可以显式指定模板参数(而不是推导它),这会导致“不匹配”参数转换为该类型。
在这个答案所有例子int i; float f;
例如,你可以这样做:
float res = multiply<float>(i, f); //i will be implicitly converted to float
或者这样:
int res = multiply<int>(i, f); //f will be implicitly converted to int
甚至这样的:
double res = multiply<double>(i, f); //both i and f will be implicitly converted to double
如果您确实想接受不同类型的参数,则需要以某种方式处理返回类型规范。这可能是最自然的做法:
template <class Lhs, class Rhs>
auto multiply(Lhs x, Rhs y) -> decltype(x * y)
{
return x * y;
}
在C++ 11之后,我们可以将签名更改为“自动乘法(Lhs x,Rhs y)”或“decltype(自动)乘法(Lhs x,Rhs y)” – AndyG
使用您提供的模板,您无法传递不同的类型。 – DeiDei