用于在 C++ 中管理特定于平台的代码的内联命名空间技术
inline namespace technique for managing platform specific code in c++
我已经看到使用 #ifdef 宏(例如特征库)来管理特定于平台的代码,但还没有看到任何人使用"内联命名空间"来管理特定于平台的代码。
下面的 github 存储库给出了具体的代码和示例用法。https://github.com/dchichkov/curious-namespace-trick/wiki/Curious-Namespace-Trick
我想知道它是否是一种可行的技术,或者是否有任何我无法看到的陷阱。以下是代码片段:
#include <stdio.h>
namespace project {
// arm/math.h
namespace arm {
inline void add_() {printf("arm addn");} // try comment out
}
// math.h
inline void add_() {
//
printf("common addn");
//
} inline namespace platform {inline void add() {add_();}}
inline void dot_() {
//
add();
//
} inline namespace platform {inline void dot() {dot_();}}
}
int main() {
project::dot();
return 1;
}
输出:
$g++ func.cpp -Dplatform=common ; ./a.out常见添加
$ g++ func.cpp -Dplatform=arm ; ./a.out手臂添加
至少有两种方法可以达到相同的结果。第一个带有命名空间。第二个 - 在类中使用静态函数。
使用命名空间:
#include <stdio.h>
namespace GenericMath
{
void add();
void dot();
}
namespace ArmMath
{
void add();
using GenericMath::dot;
}
namespace GenericMath
{
void add()
{
printf("generic add");
}
void dot()
{
Math::add();
printf("generic dot");
}
}
namespace ArmMath
{
void add()
{
printf("arm add");
}
using GenericMath::dot;
}
int main()
{
Math::dot();
return 1;
}
使用类:
#include <stdio.h>
class GenericMath
{
public:
static void add();
static void dot();
};
class ArmMath : public GenericMath
{
public:
static void add();
};
void GenericMath::add()
{
printf("generic add");
}
void GenericMath::dot()
{
printf("generic dot");
Math::add();
}
void ArmMath::add()
{
printf("arm add");
}
int main()
{
Math::add();
Math::dot();
return 1;
}
IMO 内联命名空间使代码的可读性降低且过于冗长。
一旦问题是与#ifdef
不同,编译器仍然编译所有不适合当前平台的代码。
因此,您不能使用它来处理特定于平台的 API。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 如何使用可视化代码和平台IO将环境变量注入CPP文件?
- 我的代码在不同的平台上给出不同的输出
- 如何在嵌入式平台中管理不同引脚输出板的代码,以实现更好的HAL管理
- 重用编译器前端的结果,以加快多个配置/平台的C++代码编译
- 在编写平台依赖代码时,请使用constexpr代替宏
- Clang没有为X86以外的其他平台编译代码
- 编写交叉平台代码时,使用char*而不是void*的任何陷阱
- 在C++中组织特定于平台的代码的推荐方法是什么?
- 用于在 Windows 平台上为 C/C++ 代码生成调用图的工具
- 如何在windows平台上调试android中的本机代码
- 用于在 C++ 中管理特定于平台的代码的内联命名空间技术
- 将C++代码从 Win32 平台更改为 WinCE
- windows上的boost.asio错误代码依赖于平台
- 如何查找不包含任何平台特定代码的Boost库
- 基于标记调度的专用化,用于C++代码中的平台识别和仿真
- 创建一个构建框架来支持编译支持多个平台的代码
- 编写平台特定代码的最佳(最干净)方式
- 使用CRTP分离平台特定的代码
- 使用Java原生代码或C++(QT,WxWidgets等)进行独立于平台的编程