如何将未命名的结构、联合、类替换为它们的命名等效项
How to replace the unnamed struct, union, class by their named equivalents?
我对我的项目进行了重构,我想摆脱所有匿名命名空间,包括类、结构、联合。我想用最简单的方法替换它们,用它们的命名等价物。据我所知,匿名名称空间的等价形式是:
这样的代码:
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"。
那么,为"问题示例"和所有可能的示例设置匿名结构,联合,类的名称最简单的方法是什么?
- 不,命名命名空间与匿名命名空间不同。匿名命名空间的主要用途是使其所有内容具有内部链接——这意味着其他编译单元不能引用它(例如调用函数)。因此,不要重命名匿名命名空间。这就像从静态函数中删除
static
说明符。 -
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];
};
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 从 XML 中读取未指定结构的每个数据成员
- C++中未命名函数指针的语法
- 未命名的非类型模板参数有什么意义?
- 在联盟中,不愿命名的未命名结构的成员是错误或GCC错误
- 可以使未命名的结构静态
- 命名结构与未命名结构的类型别名
- 如何在C 类的初始化器列表中使用未命名结构初始化成员结构
- 是否可以初始化未命名结构的std::数组
- 外部未命名结构对象定义
- 为什么不能将未命名结构用作尾随返回类型
- 向前声明未命名结构的 typedef
- C++在构造函数中初始化了未命名的结构成员
- 在for循环初始化语句中声明未命名结构体
- 使用-Wpedantic选项编译c++ 11:是否有一个选项可以只禁用关于未命名结构的警告
- 未命名结构的前向声明
- 未命名的结构可以继承吗?
- 如果使用未命名结构体或未定义标记实现不透明指针
- 如何将未命名的结构、联合、类替换为它们的命名等效项