Search code examples
c++compiler-errorsmacrosc-preprocessorpointer-to-member

Accessing pointer to data member using macro results in "error: expected unqualified-id before ‘*’ token"


Minimal code of the bigger problem:

struct S { int i; };
typedef int (S::*Type);

Type foo (int) { return &S::i; }
#define FOO(X) *foo(X)

int main ()
{
  S s;
  s.*foo(0) = 0; // ok
  s.FOO(0) = 0; // error  <--- ?? 
}

If foo() method is replaced with FOO() macro to avoid '*', then it results in the error posted in title. When I checked the preprocessing using g++ -E option, then both the "ok" & "error" lines look same.
Why is this error with macro?


Solution

  • With clang 3.8 I got the next output for your program:

    # 1 "test.cpp"
    # 1 "<built-in>" 1
    # 1 "<built-in>" 3
    # 325 "<built-in>" 3
    # 1 "<command line>" 1
    # 1 "<built-in>" 2
    # 1 "test.cpp" 2
    struct S { int i; };
    typedef int (S::*Type);
    
    Type foo (int) { return &S::i; }
    
    
    int main ()
    {
      S s;
      s.*foo(0) = 0;
      s. *foo(0) = 0;
    }
    

    One can see the space in the line:

    s. *foo(0) = 0;
    

    This space is the reason for "expected the unqualified-id before..." error. The space itself should be a product of token spacing.

    I do not know why g++ does not show the space. Possibly it's a compiler bug concerning representing the output of preprocessing.