gpt4 book ai didi

c++ - 解析const和非常量成员函数指针

转载 作者:行者123 更新时间:2023-12-01 19:43:52 25 4
gpt4 key购买 nike

在下面的代码片段中,我希望能够从 doWork 调用 A::foo

但是,由于 foo 有两个重载( const 和非 const ),编译器无法解析我指的是哪一个重载调用doWork。有没有办法告诉编译器我的意思是哪一个。

我无法更改struct A

我可以在 doWork 的签名或 doWork 的调用中做一些事情来始终选择 const 吗?

我知道的一个解决方案是将函数指针类型作为 doWork 的参数而不是模板(就像这样)void doWork(void (A::*fun)(void) const){但这有点难看,我希望找到一个基于模板的解决方案(如果存在)

struct A{
void foo() const {
}
void foo(){
}
void bar(){
}
void bar() const {
}
};

template<typename F>
void doWork(F fun){
const A a;
(a.*fun)();
}

int main()
{
doWork(&A::foo); //error: no matching function for call to ‘doWork()’
doWork(&A::bar); // error: no matching function for call to ‘doWork()’
return 0;
}

最佳答案

您可以使用static_cast来指定应该使用哪一个。

static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type, as in

std::for_each(files.begin(), files.end(),
static_cast<std::ostream&(*)(std::ostream&)>(std::flush));

例如

doWork(static_cast<void (A::*)(void) const>(&A::foo));
doWork(static_cast<void (A::*)(void) const>(&A::bar));

或者显式指定模板参数。

doWork<void (A::*)(void) const>(&A::foo);
doWork<void (A::*)(void) const>(&A::bar);

关于c++ - 解析const和非常量成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com