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?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Qiufeng54321
  • 169
  • 11
  • you have to show how you are using the macro. The macro alone does not produce an error only its expansion, right? – 463035818_is_not_an_ai May 16 '19 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. – Eljay May 16 '19 at 11:30
  • seems to be fine here: https://wandbox.org/permlink/8VhJL5JPo68tEa1T (after making the member public and adding the missing `;`) – 463035818_is_not_an_ai May 16 '19 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 https://stackoverflow.com/questions/2402579/function-pointer-to-member-function – aschepler May 16 '19 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. – Peter May 16 '19 at 11:31
  • @aschepler yes -facepalm- sorry for that ;) – 463035818_is_not_an_ai May 16 '19 at 11:32

1 Answers1

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.

P.W
  • 26,289
  • 6
  • 39
  • 76