C ++重载方法指针

时间:2010-12-06 08:49:46

标签: c++

如何获取指向方法特定重载的方法指针:

struct A {
    void f();
    void f(int);
    void g();
};

我知道

&A::g

是指向g的指针。但是如何获得指向ff(int)

的指针

3 个答案:

答案 0 :(得分:34)

(void (A::*)()) &A::f
(void (A::*)(int)) &A::f

函数指针和成员函数指针具有此功能 - 可以通过分配或转换结果来解决重载。

如果函数是静态的,那么你应该将它们视为普通函数:

(void (*)()) &A::f;
(void (*)(int)) &A::f;

甚至

(void (*)()) A::f;
(void (*)(int)) A::f;

答案 1 :(得分:9)

您只需要投射&A::f的结果以消除歧义:

static_cast<void (A::*)()>(&A::f); // pointer to parameterless f
static_cast<void (A::*)(int)>(&A::f); // pointer to f which takes an int

答案 2 :(得分:5)

感谢Stefan Pabst提出以下想法,他在ACCU 2015上进行了五分钟的闪电演讲。我用标签类型对其进行了扩展,以便通过cv限定符和/或参考限定符以及C +来解决重载问题+17变量模板,以避免必须键入额外的括号,否则需要。

此解决方案的工作原理与基于强制转换的答案相同,但您不必重新声明函数的返回类型,或者在成员函数的情况下,不必重新声明函数所属的类的名称因为编译器能够推断出这些东西。

bool free_func(int, int) { return 42; }
char free_func(int, float) { return true; }
struct foo {
    void mem_func(int) {}
    void mem_func(int) const {}
    void mem_func(long double) const {}
};

int main() {
    auto f1 = underload<int, float>(free_func);
    auto f2 = underload<long double>(&foo::mem_func);
    auto f3 = underload<cv_none, int>(&foo::mem_func);
    auto f4 = underload<cv_const, int>(&foo::mem_func);
}

实施underload模板的代码是here