Namespaces in C(C 中的命名空间)
问题描述
有没有办法(ab)使用 C 预处理器来模拟 C 中的命名空间?
Is there a way to (ab)use the C preprocessor to emulate namespaces in C?
我的想法是这样的:
#define NAMESPACE name_of_ns
some_function() {
some_other_function();
}
这将被翻译成:
name_of_ns_some_function() {
name_of_ns_some_other_function();
}
推荐答案
当使用命名空间前缀时,我通常为缩短的名称添加宏,可以在包含标题之前通过 #define NAMESPACE_SHORT_NAMES 激活.标头 foobar.h 可能如下所示:
When using namespace prefixes, I normally add macros for the shortened names which can be activated via #define NAMESPACE_SHORT_NAMES before inclusion of the header. A header foobar.h might look like this:
// inclusion guard
#ifndef FOOBAR_H_
#define FOOBAR_H_
// long names
void foobar_some_func(int);
void foobar_other_func();
// short names
#ifdef FOOBAR_SHORT_NAMES
#define some_func(...) foobar_some_func(__VA_ARGS__)
#define other_func(...) foobar_other_func(__VA_ARGS__)
#endif
#endif
如果我想在包含文件中使用短名称,我会这样做
If I want to use short names in an including file, I'll do
#define FOOBAR_SHORT_NAMES
#include "foobar.h"
我发现这是一个比使用 Vinko Vrsalovic 描述的命名空间宏(在评论中)更清洁、更有用的解决方案.
I find this a cleaner and more useful solution than using namespace macros as described by Vinko Vrsalovic (in the comments).
这篇关于C 中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C 中的命名空间
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
