Skip to content

Instantly share code, notes, and snippets.

@ytxmobile98
Created February 29, 2024 03:27
Show Gist options
  • Select an option

  • Save ytxmobile98/c0c713cc1c8357621b213aaea9025da7 to your computer and use it in GitHub Desktop.

Select an option

Save ytxmobile98/c0c713cc1c8357621b213aaea9025da7 to your computer and use it in GitHub Desktop.
C++ pimpl example
// 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