I've seen variants of this question asked, but they usually involve functions returning the same type. Here is my code:
#include <iostream>
#include <functional>
#include <map>
using namespace std;
void checkType(int x){
cout << "we got an int: " << x << endl;
}
void checkType(float x){
cout << "we got a float: " << x << endl;
}
int getInt(){
return 1;
}
float getFloat(){
return -101.23f;
}
int main(){
map<string, function<float()> > myMap({
{"int", getInt},
{"float", getFloat}
});
checkType(myMap["int"]());
checkType(myMap["float"]());
return 1;
}
The goal here is to call different versions of an overloaded function (checkType) depending on what the mapped function returns. Obviously the checkType(float) function ends up getting called twice because my map thinks all its functions return floats.
Is there a good way to do this? And is it at all good practice? I've found a different solution, but I think if something like this is legitimate it could be pretty sexy.
As you already found out, the way you implemented it, is not going to work, since the functions stored in map are returning float.
A proper way is to use type erasure, but if you use void* you have to take care of proper casting. Another option is to use boost::any, or QVariant.
This example uses const void* to erase types :
#include <iostream>
#include <functional>
#include <map>
using namespace std;
void callForInt(const void* x){
const int* realX = static_cast < const int* >( x );
cout << "we got an int: " << *realX << endl;
}
void callForFloat(const void* x){
const float* realX = static_cast < const float* >( x );
cout << "we got a float: " << *realX << endl;
}
int main(){
map<string, function<void(const void*)> > myMap({
{"int", callForInt},
{"float", callForFloat}
});
const int v1 = 1;
const float v2 = -101.23f;
myMap["int"](&v1);
myMap["float"](&v2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With