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
226 views
in Technique[技术] by (71.8m points)

c++ - How to get the address of an overloaded member function?

I'm trying to get a pointer to a specific version of an overloaded member function. Here's the example:

class C
{
  bool f(int) { ... }
  bool f(double) { ... }

  bool example()
  {
    // I want to get the "double" version.
    typedef bool (C::*MemberFunctionType)(double);
    MemberFunctionType pointer = &C::f;   // <- Visual C++ complains
  }
};

The error message is "error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'MemberFunctionType'"

This works if f is not overloaded, but not in the example above. Any suggestion?

EDIT

Beware, the code above did not reflect my real-world problem, which was that I had forgotten a "const" - this is what the accepted answer points out. I'll leave the question as it is, though, because I think the problem could happen to others.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Well, i'll answer what i put as comment already so it can be accepted. Problem is with constness:

class C
{
  bool f(int) { ... }
  bool f(double) const { ... }

  bool example()
  {
    // I want to get the "double" version.
    typedef bool (C::*MemberFunctionType)(double) const; // const required!
    MemberFunctionType pointer = &C::f;
  }
};

Clarification:

The original question didn't contain that const. I did a wild guess in the comments whether he possibly has f being a const member function in the real code (because at a yet earlier iteration, it turned out yet another thing was missing/different to the real-world code :p). He actually had it being a const member function, and told me i should post this as an answer.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...