如何在另一个 #define 中实现 #define
How to implement a #define in another #define?
之前的问题描述是模棱两可的,所以我修改了下面的内容。谢谢。
我想实现一些这样的宏:
#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__
宏(也可以间接使用字符串化和连接)
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如何在另一个 #define 中实现 #define
- 在C++中使用#define宏可以从不同的命名空间中选择实现