如何使结构类型定义在联合之外可见
How to make struct type definitions visible outside a union C++
当我在g++下编译时,我一直得到以下错误(这些是更长的代码段)
错误:无效使用不完整类型'const struct cmp_bk(const void*, const void*)::bk'
错误:前向声明const struct cmp_bk(const void*, const void*)::bk
代码如下:
static union {
struct tt { /* Transposition table entry */
unsigned short hash; /* - Identifies position */
short move; /* - Best recorded move */
short score; /* - Score */
char flag; /* - How to interpret score */
char depth; /* - Remaining search depth */
} tt[CORE];
struct bk { /* Opening book entry */
unsigned long hash; /* - Identifies position */
short move; /* - Move for this position */
unsigned short count; /* - Frequency */
} bk[CORE];
} core;
在程序的后面,我们定义了新的结构体a, b
static int cmp_bk(const void *ap, const void *bp)
{
const struct bk *a = (bk*) ap;
const struct bk *b = (bk*) bp;
if (a->hash < b->hash) return -1;
if (a->hash > b->hash) return 1;
return (int)a->move - (int)b->move;
}
我们可能(?)在访问联合之外的结构体bk时遇到问题
可以在联合外声明结构体:
struct tt { /* Transposition table entry */
unsigned short hash; /* - Identifies position */
short move; /* - Best recorded move */
short score; /* - Score */
char flag; /* - How to interpret score */
char depth; /* - Remaining search depth */
};
struct bk { /* Opening book entry */
unsigned long hash; /* - Identifies position */
short move; /* - Move for this position */
unsigned short count; /* - Frequency */
};
static union {
struct tt tt[CORE];
struct bk bk[CORE];
} core;
这是将C代码编译为c++的糟糕尝试。您不能在匿名类型中定义类型并期望能够访问它。因此,修复后的代码是
struct tt_type { /* Transposition table entry */
unsigned short hash; /* - Identifies position */
short move; /* - Best recorded move */
short score; /* - Score */
char flag; /* - How to interpret score */
char depth; /* - Remaining search depth */
};
struct bk_type { /* Opening book entry */
unsigned long hash; /* - Identifies position */
short move; /* - Move for this position */
unsigned short count; /* - Frequency */
};
static union {
tt_type tt[CORE];
bk_type bk[CORE];
} core;
static int cmp_bk(const void *ap, const void *bp)
{
const bk_type *a = (const bk_type*) ap;
const bk_type *b = (const bk_type*) bp;
if (a->hash < b->hash) return -1;
if (a->hash > b->hash) return 1;
return (int)a->move - (int)b->move;
}
现在,让我们看看为什么这不是c++代码。首先,这些结构体使用起来很麻烦,至少需要添加构造函数。其次,联合并不是真正的类型安全的——使用boost::variant
代替。第三,cmp_bk
。让它成为operator==(const bk_type&, const bk_type&)
-没有指针,没有void*
,没有愚蠢的铸造。第四,固定大小的数组——几乎总是一个坏主意,会带来各种各样的问题。使用std::vector
代替。到现在为止,我已经没有理智了,所以我要结束了。
相关文章:
- std::vector的包装器,使数组的结构看起来像结构的数组
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 尝试将指针与结构一起使用时出错
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 从静态库使用时隐藏不透明结构的内容
- 是否可以使一个类成为两个不同层次结构的子类?
- 如何在结构内使操作员<<过载
- 我将如何获得正确的公式结构以使我的程序C++中的侧 c?
- 如何使结构内部的可变参数模板可以在外部访问?
- 使结构的行为类似于 std::tuple
- 如何使结构一次只存储一个变量?C++
- 使结构内定义的枚举具有全局范围C++
- 使结构体在 C 中常量
- 是否可以使结构直接返回值
- std::向量使结构排序变慢?C++
- 如何使结构类型定义在联合之外可见
- 使结构体的所有数学运算符操作同一成员
- 为什么C++不使结构更紧密?
- 如何使c++结构体包含其他结构体作为成员变量