Jak ten kod poprawić aby nie trzeba było jawnie podawać typu dla drugiego parametru tylko kompilator sam zrobił konwersję typów
#include <algorithm> // std::lower_bound
#include <vector>
#include <string>
#include <cstdint>
// indeks najblizszej wartosci dla zadanego "x"
// na podstawie https://alexsm.com/cpp-closest-lower-bound/
template <typename F>
size_t search_closest(const std::vector<F>& sorted_array, F x)
{
auto iter_geq = std::lower_bound(
sorted_array.begin(),
sorted_array.end(),
x
);
if (iter_geq == sorted_array.begin()) {
return 0;
}
double a = *(iter_geq - 1);
double b = *(iter_geq);
if (std::abs(x - a) < std::abs(x - b)) {
return iter_geq - sorted_array.begin() - 1;
}
return iter_geq - sorted_array.begin();
}
int main()
{
std::vector<uint32_t> v_uint32_t;
std::vector<int32_t> v_int32_t;
auto testInt = search_closest(v_int32_t,1);
auto testUInt = search_closest(v_uint32_t,1); // tutaj kompilator powinien sie domyślić ze chce zamienić int -> uint32_t
// auto testUInt = search_closest(a.readVectorU32("a"),(uint32_t)1);
return 0;
}
https://godbolt.org/z/4d3qYc1Kd
<source>:38:33: error: no matching function for call to 'find_closest(std::vector<unsigned int="int">&, int)' 38 | auto testUInt = find_closest(v_uint32_t,1); | ~~~~~~~~~~~~^~~~~~~~~~~~~~