如何将未命名的结构、联合、类替换为它们的命名等效项

How to replace the unnamed struct, union, class by their named equivalents?

本文关键字:未命名 结构 联合 替换      更新时间:2023-10-16

我对我的项目进行了重构,我想摆脱所有匿名命名空间,包括类、结构、联合。我想用最简单的方法替换它们,用它们的命名等价物。据我所知,匿名名称空间的等价形式是:

这样的代码:

namespace { namespace-body }

等价于:

  namespace unique { /* empty body */ }
  using namespace unique;
  namespace unique { namespace-body }

链接:匿名命名空间歧义

在这种简单的情况下,为结构体、联合体、类设置唯一的名称就足够了:

1)这样的代码:

typedef struct { int a; void func() {}; } s1;

等价于

typedef struct unique { int a; void func() {}; } s1;
2)这样的代码:
    struct vec3 { 
            struct {
                    class
                    {
                        public:
                        void foo();
                    } bar;
                float x, y, z;
            } hotel; 
            float xyz[3];
    };
int main() {
    vec3 v;
    return 0;
}

等价于:

struct vec3 { 
        struct wigwam {
                class skyscraper
                {
                    public:
                    void foo();
                } bar;
            float x, y, z;
        } hotel; 
        float xyz[3];
};
int main() {
    vec3 v;
    return 0;
}

但是在这种情况下我该怎么做,我不知道:

//Problem example
struct vec3 { 
        struct {
                class
                {
                    public:
                    void foo();
                } bar;  
            float x, y, z;
        } ; 
        float xyz[3];
};
int main() {
    vec3 v;
    v.x = 10; //direct access to the internal variable of anonymous struct.
    return 0;
}
如我们所见,可以用与匿名结构体是匿名命名空间相同的方式访问匿名结构体的成员。但不可能以类似的方式定义struct。例如:
  struct unique { /* empty body */ }
  using namespace unique;
  struct unique { namespace-body }

也不可能在struct中定义一个命名空间,所以在这个例子中,不可能只在"namespace"关键字上替换"struct"。

那么,为"问题示例"和所有可能的示例设置匿名结构,联合,类的名称最简单的方法是什么?

  1. 不,命名命名空间与匿名命名空间不同。匿名命名空间的主要用途是使其所有内容具有内部链接——这意味着其他编译单元不能引用它(例如调用函数)。因此,不要重命名匿名命名空间。这就像从静态函数中删除static说明符。
  2. typedef struct { int a; void func() {}; } s1;可以用struct s1 { int a; void func() {} };代替,不需要额外的"唯一"标识符。这同样适用于union。整个typedef struct { /*def*/ } Blah;结构实际上是C的残余,在c++中没有必要。

对于您的实际问题示例:内部结构除了引入填充字节之外没有太大影响。所以这应该是等价的,并完成工作:

//Problem example, revisited
struct vec3 { 
  class Bar {
  public:
    void foo();
  };
  Bar bar;
  float x, y, z;
  float xyz[3];
};