Passing an initialization list to a macro

前端 未结 3 2224
时光取名叫无心
时光取名叫无心 2021-02-18 18:07

Why doesn\'t the commented out line in the following program compile?

#include 
#include 
using namespace std;

#define F1(a) 1

in         


        
相关标签:
3条回答
  • 2021-02-18 18:54

    The preprocessor does not know about {} initialisation. It sees the comma and thinks that's the start of a new macro argument. And then the next one. Only brackets () are things that it knows about.

    [C++11: 16.3/11]: The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments. [..]

    0 讨论(0)
  • 2021-02-18 19:06

    A macro is not a function. It interprets your input vector<int>{1,2,3} as 3 inputs, which are vector<int>{1,2 and 3}. You can change this by making it an expression (vector<int>{1,2,3}) (as you already did).

    Everything in parantheses is an expression and vector<int>(...) is a (*special member-)function so the preprocessor sees it as one expression.

    0 讨论(0)
  • 2021-02-18 19:14

    Another workaround is to transform your macro into a variadic macro

    #define F1(...) 1
    

    Or, in a more general case:

    #define M(a) a
    

    into

    #define M(...) __VA_ARGS__
    
    0 讨论(0)
提交回复
热议问题