gpt4 book ai didi

c++ - 将参数传递给模板

转载 作者:太空宇宙 更新时间:2023-11-04 15:33:40 25 4
gpt4 key购买 nike

我有这个模板:

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++ - 将参数传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com