小编Dum*_*i B的帖子

将不同类型的参数传递给函数模板

考虑这个模板:

template<typename t>
t add(t a, t b) {
    return a+b;
}
Run Code Online (Sandbox Code Playgroud)

如何传递不同类型的参数,以便返回值为:

  • int如果两个参数都是类型int.

  • float如果其中一个参数是类型的float.

  • float如果两个参数都是类型float.

我也尝试过为模板设置多个参数:

template<typename t, typename c>
Run Code Online (Sandbox Code Playgroud)

使用它们作为函数参数,因此它们可以是不同的(t add(t a, c b))但是我无法解决的问题是如何根据返回类型更改函数类型(int,float,double等)?

c++ templates function

12
推荐指数
3
解决办法
1933
查看次数

标签 统计

c++ ×1

function ×1

templates ×1