For example, I have something need to do depend on user input:
test.cpp
#include <iostream> #include <fstream> int main(){ std::string input; std::cin >> std::noskipws >> input; if(input=="A"){ std::cout << "A selected" << std::endl; }else if(input=="B"){ std::ofstream myfile; myfile.open ("test_log.txt"); myfile << time(NULL); myfile.close(); std::cout << "time saved" << std::endl; }else{ std::cout << "error" << std::endl; } return 0; }
now has option A and B,and it is violating open closed principle because when adding new condition,e.g.: option "C",needs to modify the if else statement in test.cpp. Is it possible to modify the code so that adding option "C" just adding a new file (class) and does not require to modify test.cpp?
I tried wrap the operation into a template class:
char a[]="A"; template<> struct st<a>{ st(){ std::cout << "A selected" << std::endl; } };
and try to call the template in main:
#include "A.h" #include "B.h" int main(){ std::string input; std::cin >> std::noskipws >> input; st<input.c_str()>(); return 0; }
so that adding a new option only needs to add a new template, but it failed to compile because the template can accept constant string only, and even it works, add new option still require to modify test.cpp to add new #include statement. Is it possible to add new option by defining a new class/new file without editing existing source code?