How do I get a pointer to a method 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 great just by replacing auto with an explicit type, but that's not what I'm looking for. I would like to tell C ++ on the right side of the equality which method I want.

+3


source to share


2 answers


The compiler cannot guess which method you are accessing unless you have specified which overload you are interested in by explicitly writing your prototype. You can do this either by injecting your variable as you said:

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

      



Or you can use the listing on the right side of the initialization:

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

      

+4


source


You cannot use here auto

as it would be ambiguous. You need to explicitly introduce your variable or use the listing on the right side to restrict the match to only one of the two candidates.



0


source







All Articles