gpt4 book ai didi

c++ - 如何将 C 结构包装在 C++ 类中并保持相同的名称?

转载 作者:行者123 更新时间:2023-11-30 04:24:33 24 4
gpt4 key购买 nike

假设 Acme 公司发布了一个有用的库,其中包含一个极其丑陋的 C API。我想将结构和相关函数包装在 C++ 类中。似乎我不能为包装类使用相同的名称,因为原始库不在命名空间内。

这样的事情是不可能的,对吧?

namespace AcmesUglyStuff {
#include <acme_stuff.h> // declares a struct Thing
}
class Thing {
public:
...
private:
AcmesUglyStuff::Thing thing;
};

链接将是一个问题。

我能想到的包装库的唯一方法,而不是用 C 库名称污染我的命名空间,是这样的 hack,在类中保留空间:

// In mything.h
namespace wrapper {
class Thing {
public:
...
private:
char impl[SIZE_OF_THING_IN_C_LIB];
};
}

// In thing.cc
#include <acme_stuff.h>
wrapper::Thing::Thing() {
c_lib_function((::Thing*)impl); // Thing here referring to the one in the C lib
}

只有这样吗?我想避免在所有类名上加上前缀,例如 XYThing 等。

最佳答案

看起来你让这件事变得比它需要的更难了。

#include "acme_stuff.h" // puts all of its names in global namespace

namespace acme {

class Thing {
public:
// whatever
private:
::Thing thing;
};

}

现在只需使用 acme::Thing 而不是 Thing

如果在全局命名空间中不包含 C 名称对您来说真的很重要,那么您需要一个间接级别:

namespace acme {

class Thing {
public:
Thing();
~Thing();
// whatever
private:
void *acme_thing;
};

}

在你的实现文件 #include "acme_stuff.h" 中,在你的构造函数中创建一个 new::Thing 对象并将其地址存储在 acme_thing,在你的析构函数中删除它,并在你的成员函数中将 acme_thing 转换为类型 ::Thing*

关于c++ - 如何将 C 结构包装在 C++ 类中并保持相同的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com