简体   繁体   English

C ++ ##宏不起作用

[英]C++ ## macro doesn't work

A macro with a ## will concatenate the two elements together, for example if you use #define sptember oct ## ober you will obtain october . 具有##的宏会将两个元素连接在一起,例如,如果您使用#define sptember oct ## ober ,则将获得october

So my problem is: I have a macro like this #define getRegByPin(pin) set ## pin than I have from 1 to 19 some defines like this: #define set0 xxx and #define set1 xxx , etc. 所以我的问题是:我有一个像这样的宏#define getRegByPin(pin) set ## pin比我从1到19有一些这样的定义: #define set0 xxx#define set1 xxx等。

But when I call my macro in code int p = getPinNo(pin); st(getRegByPin(p), p, to); 但是当我在代码int p = getPinNo(pin); st(getRegByPin(p), p, to);调用宏时, int p = getPinNo(pin); st(getRegByPin(p), p, to); int p = getPinNo(pin); st(getRegByPin(p), p, to); it replaces getRegByPin(p) with setp instead of set0 or set13 or etc. 它取代getRegByPin(p)setp的,而不是set0set13或等

What can i do? 我能做什么?

Thx for help! 谢谢! You are awesome! 你真棒! :) :)

The C preprocessor (and C++ has just inherited it), just does textual substitution. C预处理程序(和C ++刚刚继承了它)仅执行文本替换。 It knows nothing of variables. 它对变量一无所知。 So given 因此给定

#define getRegByPin(pin) set ## pin
const int p = 5;

getRegByPin(p);  // Will expand to setp, not set5

From the syntax, I guess that set0 to set13 are constants. 从语法上,我猜set0set13是常量。 Do they have values you can calculate? 他们有可以计算的值吗? For example: 例如:

auto getRegByPin(int pin) { return set0+pin; }  // or (set0 << pin)

If not, you are going to need a constant array which you can index: 如果没有,您将需要一个可以索引的常量数组:

auto getRegByPin(int pin) {
    static const setType_t pins[16] = { set0, set1, set2 ... set15};
    return pins[pin];
}

If they are not constants, but functions, your array will need to be an array of function pointers. 如果它们不是常量而是函数,则您的数组将需要是一个函数指针数组。

Prefer to use functions than the preprocessor. 比预处理器更喜欢使用功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM