-
-
Save czyang/62114ec261bdabed44caf0c84e382f27 to your computer and use it in GitHub Desktop.
My version of pimpl
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
// My version of pimpl ([email protected]) | |
// See http://en.cppreference.com/w/cpp/language/pimpl | |
#include <iostream> | |
// interface (widget.h) | |
class widget { | |
struct impl; | |
public: | |
static widget* create(int); // replacement of new | |
void release() const; // replacement of delete | |
void draw() const; // public API that will be forwarded to the implementation | |
void draw(); | |
bool shown() const { return true; } // public API that implementation has to call | |
}; | |
// implementation (widget.cpp) | |
#define DESC_SELF impl * self = static_cast<impl *>(this); | |
#define CONST_SELF const impl * self = static_cast<const impl *>(this); | |
struct widget::impl : widget { | |
int n; // private data | |
impl(int n) : n(n) {} | |
}; | |
widget * widget::create(int n) { | |
return new impl(n); | |
} | |
void widget::release() const { | |
CONST_SELF | |
delete self; | |
} | |
void widget::draw() const { | |
CONST_SELF | |
if(self->shown()) { // this call to public member function requires the back-reference | |
std::cout << "drawing a const widget " << self->n << '\n'; | |
} | |
} | |
void widget::draw() { | |
DESC_SELF | |
if(self->shown()) { | |
std::cout << "drawing a non-const widget " << self->n << '\n'; | |
} | |
} | |
// user (main.cpp) | |
int main() | |
{ | |
widget *w = widget::create(7); | |
const widget *w2 = widget::create(8); | |
w->draw(); | |
w2->draw(); | |
w->release(); | |
w2->release(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment