如何评估宏函数的算术表达式以传递给C预处理器中的另一个宏函数?

时间:2022-11-25 10:48:23

how can I make this example code work?(In C or C++)

如何使这个示例代码工作?(在C或C ++中)

The cout is just for example.I want evaluate the correct decremented number

cout就是例如。我想评估正确的递减数字

#define PRINT_1 std::cout<<"One : " <<1;
#define PRINT_2 std::cout<<"Two : " <<2;

#define DEC_AND_PRINT(number) PRINT_##number-1

When I call DEC_AND_PRINT(3) , I expect this:

当我调用DEC_AND_PRINT(3)时,我希望这样:

DEC_AND_PRINT(3)  PRINT_##(3-1) -> PRINT_2 -> std::cout<<"Two : "<<2

But the compiler give-me an error :

但编译器给我一个错误:

GCC : error: 'PRINT_3' was not declared in this scope...

GCC:错误:'PRINT_3'未在此范围内声明...

GCC : note: in expansion of macro 'DEC_AND_PRINT' DEC_AND_PRINT(3)

GCC:注意:扩展宏'DEC_AND_PRINT'DEC_AND_PRINT(3)

How I can decrement the argument?

我怎么能减少这个论点呢?

Basically, I'm trying to make a macro function get a number and call another macro function in syntax _name_of_macro_decremented_number.

基本上,我正在尝试使宏函数获取一个数字,并在语法_name_of_macro_decremented_number中调用另一个宏函数。

1 个解决方案

#1


0  

Thanksx for all.

谢谢大家。

There is no way to do what i wanna do.The Preprocessor cannot evalute an expression an use the result in an concatenation ##.

没有办法做我想做的事情。预处理器无法评估表达式,并在串联##中使用结果。

So im change the code to use recursion , and write all combinations in hand,like:

所以我改变代码使用递归,并编写所有组合,如:

CALL DefinePointer(T)

DefinePointer_1(T)

Define T * -> Call DefinePointer_2( T*)

定义T * - >调用DefinePointer_2(T *)

                DefinePointer_2( T*)
                Define T**  -> Call DefinePointer_3(T**)
                                    DefinePointer_3(T**)
                                  Define T*** -> Call DefinePointer_4(T****)                     

This is only a piece of code, but there is a lot more. I had to write a lot but in the end it worked, and it was possible to write algorithms and data structures for any kind of data.

这只是一段代码,但还有很多。我不得不写很多东西,但最终它有效,并且可以为任何类型的数据编写算法和数据结构。

#1


0  

Thanksx for all.

谢谢大家。

There is no way to do what i wanna do.The Preprocessor cannot evalute an expression an use the result in an concatenation ##.

没有办法做我想做的事情。预处理器无法评估表达式,并在串联##中使用结果。

So im change the code to use recursion , and write all combinations in hand,like:

所以我改变代码使用递归,并编写所有组合,如:

CALL DefinePointer(T)

DefinePointer_1(T)

Define T * -> Call DefinePointer_2( T*)

定义T * - >调用DefinePointer_2(T *)

                DefinePointer_2( T*)
                Define T**  -> Call DefinePointer_3(T**)
                                    DefinePointer_3(T**)
                                  Define T*** -> Call DefinePointer_4(T****)                     

This is only a piece of code, but there is a lot more. I had to write a lot but in the end it worked, and it was possible to write algorithms and data structures for any kind of data.

这只是一段代码,但还有很多。我不得不写很多东西,但最终它有效,并且可以为任何类型的数据编写算法和数据结构。