diff --git a/CPP/CRTP/example/main.cpp b/CPP/CRTP/example/main.cpp index 3039948..4bbbd67 100644 --- a/CPP/CRTP/example/main.cpp +++ b/CPP/CRTP/example/main.cpp @@ -1,14 +1,138 @@ +#include #include +// https://www.modernescpp.com/index.php/c-is-still-lazy -struct Shape +// +// CRTP base class of pin +// + +/* + avoiding virtual call (static polymorphism) +*/ + +template +struct PinBase { - + void set(bool logic) + { + static_cast(this)->setImp(logic); + } + + void toggle() + { + static_cast(this)->toggleImp(); + } + + bool get(void) + { + return static_cast(this)->getImp(); + } + + private: + + // + // base implementations + // + + void setImp() + { + std::cout << "base implementation of set()!" << std::endl; + } + + void toggleImp() + { + std::cout << "base implementation of toggle()!" << std::endl; + } + + bool getImp(void) + { + std::cout << "base implementation of get()!" << std::endl; + return true; + } }; +// +// implementations +// + +struct STM32_Pin : PinBase +{ + STM32_Pin() + { + std::cout << "created STM32_Pin" << std::endl; + } + + void setImp(bool logic) + { + std::cout << "stm32 pin set to " << logic << std::endl; + } + + void toggleImp() + { + std::cout << "toggled stm32 pin" << std::endl; + } + + bool getImp() + { + return true; + } + + + void STM32_stuff() + { + std::cout << "STM_32 specific stuff" << std::endl; + } +}; + +struct AVR_Pin : PinBase +{ + AVR_Pin() + { + std::cout << "created AVR_Pin" << std::endl; + } + + void setImp(bool logic) + { + std::cout << "AVR pin set to " << logic << std::endl; + } + + void toggleImp() + { + std::cout << "toggled AVR pin" << std::endl; + } + + bool getImp() + { + return true; + } + + void avr_stuff() + { + std::cout << "AVR specific stuff" << std::endl; + } +}; + +template +void foo(T& base) +{ + base.set(true); + base.set(false); + base.toggle(); +} int main(void) { - std::cout << "CRTP example" <