1

This problem is caused when I want to get the address of Functions in Macros after the sign(::).It always has a trailing whitespace which reports an error.

I'm using G++ in Mac OS Mojave i386.

For example, I have the class:

struct A{
  void b();
};

and there's a macro:

#define ACC(name) &A::name

I use this to get the pointer of A::b:

void(*accab)() = ACC(b);

And I will get the error like this:

error: cannot initialize a variable of type 'void (*)()' with an rvalue of type 'void (A::*)()'

After that I tried putting a bracket but I got this:

error: call to non-static member function without an object argument

Is there any way to solve the problem so that the pointer can be gotten by macro?

6
  • you have to show how you are using the macro. The macro alone does not produce an error only its expansion, right? Commented May 16, 2019 at 11:27
  • 3
    Somewhere you have code with a void (*)() signature. Such a function pointer cannot hold a void (A::*)(). The types do not match. Commented May 16, 2019 at 11:30
  • seems to be fine here: wandbox.org/permlink/8VhJL5JPo68tEa1T (after making the member public and adding the missing ;) Commented May 16, 2019 at 11:30
  • 1
    The macro isn't the actual problem. This won't work because a pointer to free function and pointer to member function are different types (you have to provide the A object to call A::b). See for example stackoverflow.com/questions/2402579/… Commented May 16, 2019 at 11:30
  • 4
    Your problem has nothing to do with using a macro. A pointer to a function is a different thing from a pointer to a non-static member function of a class. The error message you describe suggests you are trying to assign one equal to the other, such is simply not allowed. Commented May 16, 2019 at 11:31

1 Answer 1

3

The type of a pointer to function is different from the type of pointer to member function.

In general, the type of pointer to any member is distinct from the type of a normal pointer.

To make this work you will have declare accab as pointer to member:

void(A::* accab)() = ACC(b);

The C++ standard has a note concerning this:

The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.