Created
September 5, 2021 01:15
-
-
Save ytxmobile98/5cf34e1a96edfd6c913143d1443fdeca to your computer and use it in GitHub Desktop.
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
| #include <iostream> | |
| #include "A.h" | |
| 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; | |
| } |
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
| #ifndef A_H | |
| #define A_H | |
| #include <iostream> | |
| #include "pimpl.h" | |
| class A; | |
| class Aimpl { | |
| friend A; | |
| private: | |
| int i = 0; | |
| friend std::ostream& operator<<(std::ostream& os, const A& a); | |
| }; | |
| class A: public Pimpl<Aimpl> { | |
| public: | |
| void inc(); | |
| void dec(); | |
| friend std::ostream& operator<<(std::ostream& os, const A& a); | |
| }; | |
| #endif |
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 "A.h" | |
| int main() | |
| { | |
| A a; | |
| a.inc(); | |
| std::cout << a; | |
| a.dec(); | |
| std::cout << a; | |
| } |
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
| .PHONY: all | |
| all: main.out | |
| main.out: *.cpp | |
| $(CXX) -g -Wall -Werror $^ -o $@ | |
| .PHONY: clean | |
| clean: | |
| -rm -rf *.out |
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
| #ifndef PIMPL_H | |
| #define PIMPL_H | |
| 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; | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment