I have functions in a superclass designed to associate a string with internal functions:
class Base
{
typedef std::function<void(double)> double_v;
bool registerInput(std::string const& key, double_v const& input) {
functions[key] = input;
}
void setInput(std::string key, double value) {
auto fit = functions.find(key);
if (fit == functions.end()) return;
fit->second(value);
}
std::map<std::string, double_v> functions;
}
The idea being that any subclass I can register functions can call them with a string and value:
SubBase::SubBase() : Base(){
Base::registerInput(
"Height",
static_cast<void (*)(double)>(&SubBase::setHeight)
);
}
void SubBase::setHeight(double h) {
....
}
Which could then be called with:
subBaseInstance.setInput("Height", 2.0);
However when I compile I'm getting the following error:
In constructor ‘SubBase::SubBase()’
error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘void (*)(double)’
What am I missing?
It's
function-pointer
.It's
member-function pointer
. They are not convertible to each other.You can use
std::bind
for thisAs others noted, the types doesn't match. However you could use
std::bind
for it to work:SubBase
is notstatic
, so it has an implicit first argument ofSubBase*
(the object you call the member function for). Hence the signature isvoid (*) (SubBase*, double)
. In C++11 you can probably (I'm not completely sure) cast it to afunction<void (SubBase*, double)>
.Using lambda functions, you can do the following: