Created
February 29, 2024 03:27
-
-
Save ytxmobile98/c0c713cc1c8357621b213aaea9025da7 to your computer and use it in GitHub Desktop.
C++ pimpl example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // PIMPL | |
| #include <iostream> | |
| #include <string> | |
| template <typename T> | |
| class Pimpl { | |
| protected: | |
| T *const impl; | |
| public: | |
| Pimpl(); | |
| ~Pimpl(); | |
| }; | |
| template <typename T> | |
| Pimpl<T>::Pimpl(): impl(new T()) {} | |
| template <typename T> | |
| Pimpl<T>::~Pimpl() { | |
| delete impl; | |
| } | |
| class Aimpl; | |
| class A: public Pimpl<Aimpl> { | |
| public: | |
| void inc(); | |
| void dec(); | |
| friend std::ostream& operator<<(std::ostream& os, const A& a); | |
| }; | |
| class Aimpl { | |
| public: | |
| int i = 0; | |
| }; | |
| void A::inc() { | |
| ++impl->i; | |
| } | |
| void A::dec() { | |
| --impl->i; | |
| } | |
| std::ostream& operator<<(std::ostream& os, const A& a) { | |
| os << a.impl->i << "\n"; | |
| return os; | |
| } | |
| int main() | |
| { | |
| A a; | |
| a.inc(); | |
| std::cout << a; | |
| a.dec(); | |
| std::cout << a; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment