Skip to content

Instantly share code, notes, and snippets.

@bilbothebaggins
Created February 11, 2023 10:00
Show Gist options
  • Save bilbothebaggins/5a1d83ba0b5759e6481caff543c46246 to your computer and use it in GitHub Desktop.
Save bilbothebaggins/5a1d83ba0b5759e6481caff543c46246 to your computer and use it in GitHub Desktop.
C++ Null-Object vs Pointer Callback
#include <iostream>
struct HelloData {
int i = 0;
const char* s = "";
};
struct CallbackBase {
virtual ~CallbackBase() = default;
virtual void Hello(HelloData const& d) = 0;
};
struct NoopCaller final : CallbackBase {
virtual void Hello(HelloData const&) override { /*noop*/ }
};
inline NoopCaller Noop;
int Resultify(int val) {
if (val >= 0 && val <= 42) {
val *= 42;
}
return val;
}
int WithPointer(int val, CallbackBase* pOpt=nullptr) {
if (pOpt) { pOpt->Hello({ val, "from WithPointer" }); }
return Resultify(val);
}
double WithObject(int val, CallbackBase& opt=Noop) {
opt.Hello({ val, "from WithObject" });
return Resultify(val);
}
// ------ different compilation units ------
struct LogCallback : CallbackBase {
std::string name = "LogCallback";
virtual void Hello(HelloData const& d) override {
std::cout << "[" << name << "]: " << d.i << " : " << d.s << "\n";
}
};
int main()
{
using std::cout;
cout << "Hello ...!\n";
LogCallback logger;
logger.name = "log from main";
WithPointer(23, &logger);
WithPointer(24);
WithObject(42, logger);
WithObject(43);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment