为不同类型参数重载函数

Overload functions for different type arguments?

本文关键字:重载 函数 类型参数      更新时间:2023-10-16

我正在考虑重载函数,这不是一种更快的执行方式吗?例如,没有使用不同的参数和输出(int, float double ecc…)多次定义函数的成瘾。

更多的理解:

// 2 ints addiction
int addic(int & a, int & b) {
  int c;
  c = a + b;
  return c;
}
// 1 int + 1 float
float addic(int & a, float & b) {
  float c;
  c = a + b;
  return c;
}

不是更快的方法吗?我需要定义所有的情况吗?

这是模板存在的原因之一(为了避免代码重复);下面是一个示例,说明如何实现作为示例使用的函数(在c++ 11中):

#include <type_traits> // for std::common_type
template<class T1, class T2>
std::common_type<T1, T2>::type addic(const T1& a, const T2& b)
{
    return a + b;
}

T1将是传递给函数的第一个参数的类型,而T2将是第二个参数的类型。

std::common_type<T1, T2>::type是T1和T2都可以转换的类型。例如,添加一个float和一个int,则类型为float

编辑:如果你想对矢量做点什么,你可以这样做:

template<class T>
void MyFunction(std::vector<T>& v)
{
    // do something with the vector v, for example:
    v.push_back(5);
}