Skip to content

Instantly share code, notes, and snippets.

@ytxmobile98
Created September 5, 2021 01:15
Show Gist options
  • Select an option

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

Select an option

Save ytxmobile98/5cf34e1a96edfd6c913143d1443fdeca to your computer and use it in GitHub Desktop.
PIMPL example
#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;
}
#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
// PIMPL
#include <iostream>
#include "A.h"
int main()
{
A a;
a.inc();
std::cout << a;
a.dec();
std::cout << a;
}
.PHONY: all
all: main.out
main.out: *.cpp
$(CXX) -g -Wall -Werror $^ -o $@
.PHONY: clean
clean:
-rm -rf *.out
#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