I've a function that is currently overloaded for different data types and takes a lambda(function pointer) to initialize those data types. I'm in process of converting them to template instances but haven't been successful yet.
Here's the overloaded version -
#include <iostream>
using namespace std;
void doSome(int (*func)(int &)){
int a;
a = 5;
int res = func(a);
cout << a << "\n";
}
void doSome(int (*func)(double &)){
double a;
a = 5.2;
int res = func(a);
cout << a << "\n";
}
int main() {
doSome([](int &a){
a += 2;
return 1;
});
doSome([](double &a){
a += 2.5;
return 1;
});
return 0;
}
Note that I've taken example of int
and double
for simplification, they might be some entirely different(and complex) types in actual code.
#include <iostream>
using namespace std;
template <typename F, typename S>
void doSome(F &func){
S a;
auto res = func(a);
cout << res << "\n";
}
template<>
void doSome<typename F, int> (F &func){
int a;
a = 5;
auto res = func(a);
cout << res << "\n";
}
template<>
void dpSome<typename F, double> (F &func){
double a;
a = 5.5
auto res = func(a);
cout << res << "\n";
}
int main() {
doSome([](int &a){
a += 2;
return 1;
});
doSome([](double &a){
a += 2.5;
return 1;
});
return 0;
}
Also while invoking templated functions, if I don't have to pass <any type hints>
to the function, that would be much better solution.