如何在另一个 #define 中实现 #define

How to implement a #define in another #define?

本文关键字:#define 实现 另一个      更新时间:2023-10-16

之前的问题描述是模棱两可的,所以我修改了下面的内容。谢谢。

我想实现一些这样的宏:

#define AddVariable(x) 
    #define x (++counter)
class Base {
 private:
  int counter = 0;
}
class Extend : public Base {
 public:
  void Handler() {
    AddVariable(ASDF);
    AddVariable(HJKL);
    // Here may add more variables.
  }
  void AnotherHandler() {
    // It calls ASDF, HJKL too.
  }
}

ASDF 和 HJKL 应该可以通过 cpp 文件中的所有处理程序使用,所以我必须在宏中定义它(尽管这不是一个好的设计)。但是我应该如何编写正确的宏来实现它(#define 不能嵌套在另一个 #define 中)?还是有其他更好的实施方式?

提前谢谢。

更新:

一个可能的实现是

#define AddVariable(x) 
  int x = ++counter;

它可以工作,但 x 不是全局的,我必须解决这个问题。

看起来您正在尝试向Base对象公开增量器,counter.cpp文件中的所有函数。

答:这是不可能的。

.cpp文件中的其他函数/对象没有对Base对象的引用,因此无法更改其任何数据。

如果要为所有Base对象维护一个计数器,可以尝试如下操作:

class Base {
public:
    static void ASDF(){counter++;}
private:
    static int counter = 0;
};

这可以调用 from 和其他函数:

void AnotherHandler() {
    Base::ASDF();
}

编辑:

class Base {
protected:
    static int counter = 0;
};
class Another : public Base{
public:
    Another(){
        counter++; // As a child of Base you have access to all of it's protected variables
    }
}

使用std::map会起作用吗?

#include <iostream>
#include <map>
#include <string>
class Base {
protected:
    void AddVariable(const std::string& name) {
        variables[name] = counter++;
    }
    int& GetVariable(const std::string& name) {
        return variables[name];
    }
private:
    int counter = 0;
    std::map<std::string, int> variables;
};
class Extend : Base {
public:
    void Handler() {
        AddVariable("ASDF");
        AddVariable("HJKL");
        // May add more variables here ...
    }
    void AnotherHandler() {
        // Use ASDF, HJKL here too
        std::cout << GetVariable("ASDF") << std::endl;
        std::cout << GetVariable("HJKL") << std::endl;
    }
};
int main()
{
    Extend e;
    e.Handler();
    e.AnotherHandler();
}

输出:

0
1

不能使用 C 预处理器执行此操作(在宏中定义宏)。

但是,有时您可以玩X宏技巧,就像这里一样。

如果你真的需要宏定义宏,切换到一些外部或非标准的预处理器,如GNU m4或gpp。

或者,使用一些外部工具(例如您自己的Python或GNU awk脚本)生成您的C++代码

最后,最近的GCC(例如GNU cpp)或Clang/LLVM提供了__COUNTER__宏(也可以间接使用字符串化和连接)