C++ macro '##' doesn't work after '->' operator

后端 未结 3 1686
青春惊慌失措
青春惊慌失措 2021-01-01 11:47

I have a shared_ptr object x, which has get and set methods as follows:

x->a_value();
x->set_a_value();
x->b_value();
x->set_b_value();
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 12:39

    The token-pasting operator (##) is used to concatenate two tokens into a single valid token.

    When you write

    x->##type##_value();
    
    • The first processed token is x.

    • The next token is formed by concatenating the token -> with type, since type is a, the result of the concatenation is ->a, which ought to be a valid token, but is not.

    Hence, you get the error: pasting formed '->a', an invalid preprocessing token.

    To fix this, just write

    x->type##_value();
    

    This way

    • The first token parsed is x.

    • The next token parsed is ->.

    • The next token is formed by concatenating the token type (which becomes a) with the token _value. This gives a_value, which is a valid token.

    • The next token is (.

    • The next token is ).

    • The last token is ;.

提交回复
热议问题