用于在 C++ 中管理特定于平台的代码的内联命名空间技术

inline namespace technique for managing platform specific code in c++

本文关键字:平台 代码 技术 命名空间 C++ 管理 于平台 用于      更新时间:2023-10-16

我已经看到使用 #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。