我一直在研究 Pimpl 习语并从中获得了各种好处。我唯一不太感兴趣的是定义函数时的感觉。
- 一旦进入标题(P def)
- 一旦到达 .cpp 的顶部(Impl def)
- 一旦进入.cpp(Impl Impl)中间
- 一旦到达 .cpp 的下端(P Impl)
我真的很喜欢减少代码差异和冗余,当我必须在当前项目中相对复杂的 Impl 中添加或更改功能时,我觉得我的代码不够完善。
我的问题是,有什么有效的方法来暗示或模板化我的类,如果我要定义一个新函数,我只需要编写一个显式定义和实现,而其余的在空间上保持接近代码中的显式内容;如果我要更改某个功能,所需的更改会尽可能少?
您可能会考虑以下一些事情:
用于最大程度地减少重复声明的 Interface 类。客户端将使用PublicImplementation
他们的代码中的类。
Pimpl.h
#ifndef PIMPL_H_
#define PIMPL_H_
#include <memory> // std::unique_ptr
class Interface
{
public:
virtual ~Interface() {}
virtual void func_a() = 0;
virtual void func_b() = 0;
};
class PublicImplementation
{
// smart pointer provides exception safety
std::unique_ptr<Interface> impl;
public:
PublicImplementation();
// pass-through invoker
Interface* operator->() { return impl.get(); }
};
#endif // PIMPL_H_
Pimpl.cpp
#include "Pimpl.h"
#include <iostream>
class PrivateImplementation
: public Interface
{
public:
void func_a() override { std::cout << "a" << '\n'; }
void func_b() override { std::cout << "b" << '\n'; }
};
PublicImplementation::PublicImplementation()
: impl(new PrivateImplementation)
{
}
最后,这就是客户端代码的作用:
Main.cpp
#include "Pimpl.h"
int main()
{
PublicImplementation pi; // not a pointer
pi->func_a(); // pointer semantics
pi->func_b();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)