Arne
Arne

Reputation: 8481

How do I get the method pointer of a class, with multiple implementations of that method?

#include <cstdio>

struct A {
    void foo(int) { printf("this is the wrong function\n"); }
    void foo() { printf("this is the right function\n"); }
};

int main() {
    auto method = &A::foo; // c++ why don't you me allow to give argument types?

    A a;
    (a.*method)();
}

I know this little example works fine with just replacing auto with an explicit type, but that is not, what I am looking for. I would like to tell c++ on the right side of the equals, which method I want.

Upvotes: 3

Views: 62

Answers (2)

Andrea Bergia
Andrea Bergia

Reputation: 5542

You can't use auto here, as it would be ambiguous. You need to explicitly type your variable or use a cast on the right-hand side to restrict the matching to only one of the two candidates.

Upvotes: 0

Luc Touraille
Luc Touraille

Reputation: 82041

The compiler cannot guess which method you refer to unless you specify which overload you are interested in, by explicitely writing its prototype. You can do that either by explicitely typing your variable, like you said:

void (A::*foo)() = &A::foo;
void (A::*fooInt)(int) = &A::foo;

Or you can use a cast on the right hand side of the initialization:

auto foo = static_cast<void (A::*)()>(&A::foo);
auto fooInt = static_cast<void (A::*)(int)>(&A::foo);

Upvotes: 4

Related Questions