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

Sum*_*itV 4 c++ member-function-pointers

在下面的代码片段中,我希望能够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 function for call to ‘doWork()’
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

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

static_cast 也可以通过执行函数到指针到特定类型的转换来消除函数重载的歧义,如

std::for_each(files.begin(), files.end(),
              static_cast<std::ostream&(*)(std::ostream&)>(std::flush));
Run Code Online (Sandbox Code Playgroud)

例如

doWork(static_cast<void (A::*)(void) const>(&A::foo));
doWork(static_cast<void (A::*)(void) const>(&A::bar));
Run Code Online (Sandbox Code Playgroud)

或者明确指定模板参数。

doWork<void (A::*)(void) const>(&A::foo);
doWork<void (A::*)(void) const>(&A::bar);
Run Code Online (Sandbox Code Playgroud)


R S*_*ahu 2

您可以使用:

template <typename T>
void doWork(void (T::*fun)() const){
    const A a;
    (a.*fun)();
}
Run Code Online (Sandbox Code Playgroud)

更通用的函数模板将使用const T a.

template <typename T>
void doWork(void (T::*fun)() const){
    const T a;
    (a.*fun)();
}
Run Code Online (Sandbox Code Playgroud)

请注意,第二个版本没有A任何假设。