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

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

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

链接将是一个问题。

我想包装库而不用C库名称污染我的 namespace 的唯一方法是这样的黑客,在类中保留空间:
// 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

如果在全局 namespace 中不使用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/

10-11 23:04
查看更多