Created
February 11, 2023 10:00
-
-
Save bilbothebaggins/5a1d83ba0b5759e6481caff543c46246 to your computer and use it in GitHub Desktop.
C++ Null-Object vs Pointer Callback
This file contains 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> | |
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