Created
February 5, 2017 20:57
-
-
Save gierwialo/b6ac2e496ca7bbdc5d62e42bfe0f53b4 to your computer and use it in GitHub Desktop.
Test of concept. How to extend API for advanced users (via GetSpell), and hide dangerous functions from beginners.
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 <memory> | |
//Interface | |
class IMagician | |
{ | |
protected: | |
virtual ~IMagician() {}; | |
typedef void(IMagician::*Spell_t)(); | |
public: | |
virtual void Hi() = 0; | |
virtual Spell_t GetSpell(const char* spell) = 0; | |
}; | |
//Advaced usage, typedefs and strings for GetSpell | |
const char* WingardiumLeviosa_s = "Wingardium Leviosa!"; | |
const char* Accio_s = "Accio!"; | |
typedef void(IMagician::*WingardiumLeviosa_t)(); | |
typedef bool(IMagician::*Accio_t)(const char* what); | |
//IMPLEMENTATION | |
class HogwartMagician : public IMagician | |
{ | |
public: | |
virtual ~HogwartMagician() {} | |
virtual void Hi(); | |
IMagician::Spell_t GetSpell(const char* spell); | |
private: | |
void WingardiumLeviosa(); | |
bool Accio(const char* what); | |
}; | |
IMagician* CreateMagician() | |
{ | |
return new HogwartMagician(); | |
} | |
void DestroyMagician(IMagician* p_magician) | |
{ | |
delete dynamic_cast<HogwartMagician*>(p_magician); | |
} | |
HogwartMagician::Spell_t HogwartMagician::GetSpell(const char* spell) | |
{ | |
if (spell == "Accio!") | |
return (Spell_t)(&HogwartMagician::Accio); | |
if (spell == "Wingardium Leviosa!") | |
return (Spell_t)(&HogwartMagician::WingardiumLeviosa); | |
return nullptr; | |
} | |
void HogwartMagician::Hi() { printf("Hi! \n"); } | |
void HogwartMagician::WingardiumLeviosa() { printf("Everything is flying! \n"); } | |
bool HogwartMagician::Accio(const char* what) { printf("I want %s \n", what); return 1; } | |
int main() | |
{ | |
std::shared_ptr<IMagician> me(CreateMagician(),DestroyMagician); | |
WingardiumLeviosa_t Say_WingardiumLeviosa = (WingardiumLeviosa_t)me->GetSpell(WingardiumLeviosa_s); | |
Accio_t Say_Accio = (Accio_t) me->GetSpell(Accio_s); | |
auto meAdv = me.get(); | |
(meAdv->*Say_Accio)("Book"); | |
(meAdv->*Say_WingardiumLeviosa)(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment