C++, use different class with preprocessor -
i have various class case0, case1, case2, etc. , switch between them using preprocessor #defines. share same interface (the same public methods) , use oop i'd prefer use preprocessor directives.
for have like:
#define caseclass case0 //#define caseclass case1 //#define caseclass case2 #define case 0 class main { public: caseclass *mycase; main() { mycase = new caseclass(); if(case==0) { mycase->foo(); // else } if(case==1) { mycase->foo(); // else } } } in way every time have switch have change defines caseclass , case. i'm wondering if there cleaner method.
edit:
i don't want use oop because different classes use different libraries. can affect compile time, , platform dependent. think preprocessor directives better bet here.
if share same interface, why need switch among them? here's better ideas.
first one: have preprocessor magic in 1 place. put in header:
#if defined(platform_one) #include "platform_one/implementation.hpp" typedef platformoneimplementation theclass; #elif defined(platform_two) #include "platform_two/implementation.hpp" typedef platformtwoimplementation theclass; #else #error no implementation available. #endif this place in project uses preprocessor. else uses theclass , nothing platform-dependent. if it's dependent, implementation class should hide it.
and mentioned above, use project configurations switch.
here's better option. put in header:
class theclass { public: theclass(); ~theclass(); // public stuff goes here. private: struct impl; std::unique_ptr<impl> pimpl; }; then have 1 .cpp file per platform , use project configurations compile right one:
// platform_one/implementation.cpp struct theclass::impl { platformspecificstuff stuff; morestuff more; }; theclass::theclass() : pimpl(new impl) {} theclass::~theclass() {} // implementation of public functions here. both of these options infinitely better littering code preprocessor switches.
Comments
Post a Comment