c ++故障转换重载函数:<未解析的重载函数类型> [英] c++ Trouble casting overloaded function: <unresolved overloaded function type>
问题描述
我在超类中设置了函数,用于将字符串与内部函数关联:
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) {
....
}
然后可以调用:
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)’
我缺少什么?
推荐答案
SubBase
不是 static
SubBase *
的第一个参数(您称为成员函数的对象)。因此签名是 void(*)(SubBase *,double)
。在C ++ 11你可能(我不完全确定)把它转换为函数
SubBase
is not static
, so it has an implicit first argument of SubBase*
(the object you call the member function for). Hence the signature is void (*) (SubBase*, double)
. In C++11 you can probably (I'm not completely sure) cast it to a function<void (SubBase*, double)>
.
使用lambda函数,您可以执行以下操作:
Using lambda functions, you can do the following:
SubBase::SubBase() : Base(){
auto myself = this;
Base::registerInput(
"Height",
[myself] (double v) { myself->setHeight (v); }
);
}
void SubBase::setHeight(double h) {
....
}
这篇关于c ++故障转换重载函数:<未解析的重载函数类型>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!