小编Sum*_*itV的帖子

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

在下面的代码片段中,我希望能够A::foodoWork.

但是,因为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 …
Run Code Online (Sandbox Code Playgroud)

c++ member-function-pointers

4
推荐指数
2
解决办法
180
查看次数

标签 统计

c++ ×1

member-function-pointers ×1