为不同类型参数重载函数
Overload functions for different type arguments?
我正在考虑重载函数,这不是一种更快的执行方式吗?例如,没有使用不同的参数和输出(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);
}
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?