【发布时间】:2017-02-14 07:54:31
【问题描述】:
我对 C++ 还很陌生,我认为重载函数总是可以的,我的意思是重载:
C++ 中的函数重载 您可以在同一范围内对同一函数名有多个定义。函数的定义必须因参数列表中的类型和/或参数数量而有所不同。您不能重载仅因返回类型不同而不同的函数声明。
但是,当我编写下面的代码时,它无法编译,而且我的印象是 std::upper_bound 无法解析它应该使用哪个比较器,尽管它看起来很容易,因为只有一个具有正确的签名。
EDIT 这些函数位于命名空间中的实用程序文件(而非类)中。
我可能完全错了,你能解释一下
- 为什么代码不能编译
- 我如何编写 2 个 lt 实现,其中不同的签名将使代码编译和运行
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
//I have a utility file where functions are defined in a namespace
namespace util{
bool lt(double y, const std::pair<double, long>& x) {
return x.first < y;
}
//If this function is commented the whole will compile and run
bool lt(const std::pair<double, long>& x, double y) {
return x.first < y;
}
}
int main()
{
std::vector<std::pair<double,long> > v;
v.push_back(std::make_pair(999., 123));
v.push_back(std::make_pair(100., 3));
v.push_back(std::make_pair(15., 13));
v.push_back(std::make_pair(10., 12));
v.push_back(std::make_pair(1., 2));
//use upper_bound
std::vector<std::pair<double,long> >::iterator it =
std::upper_bound(v.begin(), v.end(), 25., util::lt);
std::cout << " it->first => " << it->first << std::endl;
}
【问题讨论】: