Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c++ - How to invoke pointer to member function when it's a class data member?

struct B
{
  void (B::*pf)(int, int);  // data member
  B () : pf(&B::foo) {}
  void foo (int i, int j) { cout<<"foo(int, int)
"; } // target method
};

int main ()
{
  B obj;
  // how to call foo() using obj.pf ?
}

In above test code, pf is a data member of B. What's the grammar rule to invoke it ? It should be straight forward, but I am not getting a proper match. e.g. If I try obj.*pf(0,0); then I get:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘pf (...)’, e.g. ‘(... ->* pf) (...)’
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like this:

(obj.*obj.pf)(0, 1);

Member access (.) has a higher precedence than a pointer to member operator so this is equivalent to:

(obj.*(obj.pf))(0, 1);

Because function call also has higher precedence than a pointer to member operator, you can't do:

obj.*obj.pf(0, 1) /* or */ obj.*(obj.pf)(0, 1)

As that would be equivalent to:

obj.*(obj.pf(0, 1)) // grammar expects obj.pf to be a callable returning a
                    // pointer to member

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...