C++两个不同函数签名的重定义错误

C++ redefinition error for two different function signatures

本文关键字:错误 定义 函数 两个 C++      更新时间:2023-10-16

我有一个类型,morton_id_t,这是一个64位的数字。我有第二种类型,它是Morton ID (morton_id_t)的位与包含树中级别信息的几个位的串联:

typedef uint64_t morton_id_t;
typedef uint64_t morton_id_lvl_t;
#define BITS (sizeof(morton_id_lvl_t) * 8)
// number of bits to store the level
#define LEVEL_BITS 6
#define LEVEL_MASK ((1 << LEVEL_BITS) - 1)
// utility functions to pull the level or morton id out of a morton_id_lvl_t
lvl_t level(morton_id_lvl_t n);
morton_id_t morton_id(morton_id_lvl_t n);
// this just strips off the level bits using the `morton_id` function...
bool isAncestor(morton_id_lvl_t ancestor, morton_id_lvl_t descendent);
// ...and calls this
bool isAncestor(morton_id_t ancestor, morton_id_t descendent);

morton_id_t只是从uint64_t typedef,即使我只需要 64 - 6 级位。

编译器抛出一个错误,指出第二个isAncestor定义重新定义了第一个定义,即使类型签名不同。

如何定义两个不同的isAncestor函数,其中一个取morton_id_lvl_t,另一个取morton_id_t

我需要使用类而不是typedef类吗?

morton_id_tmorton_id_lvl_t是相同的,因此isAncestor签名也相同。

typedef不会创建新类型,而是创建现有类型的别名。

不幸的是,typedef 只为类型引入了一个新名称,它不会创建新类型。

您可以将它们包装在结构中以将它们转换为不同的类型:

struct morton_id_t
{
    uint64_t id;
};
struct morton_id_lvl_t
{
    uint64_t id_lvl;
};

或者可能(不是 100% 确定它是有效的):

struct morton_id_lvl_t
{
    uint64_t id:58;
    uint64_t level:6;
};

这也将为转换函数提供类型安全性。