PImpl 并不能使我免于导出 STL
PImpl Doesn't Save Me from having to Export STL
我采用了PImpl设计,以避免从动态库中导出STL。
旧:
//In header file
class Foo{
public:
const map<char, char>& getMap() {return _map;}
private:
map<char, char> _map;
};
新增:
//In header file
class Foo{
public:
Foo();
~Foo();
const map<char, char>& getMap();
private:
struct Impl;
Impl* _pimpl;
};
//In implementation file
struct Foo::Impl{
map<char, char> _map;
}
Foo::Foo(): _pimpl(new Impl){}
Foo::~Foo(){delete _pimpl;}
const map<char, char>& Foo::getMap(){return _pimpl->_map;}
然而,明显的问题是,我仍然必须将map
作为库的一部分导出。我不想停止返回STL,但我看不到绕过它的方法。有没有另一种范式仍然可以让我返回STL,而不必导出它?
解决方案是不在类的接口中使用std::map
,而是实现所需的方法子集。例如,假设您希望通过operator[]
、访问读写元素
// Foo.h
class Foo{
public:
Foo();
~Foo();
const char& operator[](char key) const;
char& operator[](char key);
private:
struct Impl;
Impl* _pimpl;
};
然后
// Foo.cpp
#include <map>
struct Foo::Impl
{
std::map<char, char> _map;
};
Foo::Foo() : _pimpl(new Impl){}
Foo::~Foo(){delete _pimpl;} // don't forget to take care of copy and assignment
const char& Foo::operator[](char key) const {return _pimpl->_map[key];}
char& Foo::operator[](char key) {return _pimpl->_map[key];}
相关文章:
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- 一个C++类可以导出几个不同的 stl 样式迭代器吗?
- STL 算法 + c'tor 不再适用于指向 C 数组的原始指针,因为指向一个过去的末端
- 模板参数适用于不同的STL容器
- 从DLL导出STL类-为什么返回类型没有警告
- 最佳 STL 变换 - 类似于三元运算符的模板函数
- 在C /STL中,是否有相当于Python范围()的紧凑型
- Ogre 如何在没有 C4251 警告的情况下在导出类中使用 STL 容器
- STL 函数类似于排序
- MFC:类似于Windows资源管理器的应用程序,可以与主线程并行导出文件
- stl或boost中是否存在用于线程间通信的线程安全结构,其行为类似于队列
- PImpl 并不能使我免于导出 STL
- PIMPL:导出具有单个STL成员的类(std::unique_ptr)
- 如何检查c++stl向量中是否存在值,并将函数应用于向量的每个元素
- CMake 导出依赖于外部库的包
- STL算法(如for_each)应用于多个参数
- 有没有类似于Thrust(GPU的并行STL)的库,但适用于GPGPU AMD Radeon
- 如何在c++中导出.stl
- 当从DLL导出STL std::basic_string模板时,我得到一个LNK2005错误
- 什么是c#等效于c++ STL填充方法