今天写代码,遇到这样一个类似如下的需求:
auto componentClassSavedByPLC = std::make_shared<ComponentClassSavedByPLC>(); m_componentClassies.emplace_back(componentClassSavedByPLC); auto componentClassSavedByDCSLocalControl = std::make_shared<ComponentClassSavedByDCSLocalControl>(); m_componentClassies.emplace_back(componentClassSavedByDCSLocalControl); auto componentClassSavedByCCS = std::make_shared<ComponentClassSavedByCCS>(); m_componentClassies.emplace_back(componentClassSavedByCCS); auto componentClassSavedBySIS_1 = std::make_shared<ComponentClassSavedBySIS_1>(); m_componentClassies.emplace_back(componentClassSavedBySIS_1); auto componentClassSavedBySIS_2 = std::make_shared<ComponentClassSavedBySIS_2>(); m_componentClassies.emplace_back(componentClassSavedBySIS_2); auto componentClassSavedBySLNIPLC = std::make_shared<ComponentClassSavedBySLNIPLC>(); m_componentClassies.emplace_back(componentClassSavedBySLNIPLC); auto componentClassSavedByPLCLocalControl = std::make_shared<ComponentClassSavedByPLCLocalControl>(); m_componentClassies.emplace_back(componentClassSavedByPLCLocalControl); auto componentClassSavedByLocalInstrument = std::make_shared<ComponentClassSavedByLocalInstrument>(); m_componentClassies.emplace_back(componentClassSavedByLocalInstrument); auto componentClassSavedByPanelInstrument = std::make_shared<ComponentClassSavedByPanelInstrument>(); m_componentClassies.emplace_back(componentClassSavedByPanelInstrument); auto componentClassSavedByBehindPanelInstrument = std::make_shared<ComponentClassSavedByBehindPanelInstrument>(); m_componentClassies.emplace_back(componentClassSavedByBehindPanelInstrument); auto componentClassSavedByLocalPanelInstrument = std::make_shared<ComponentClassSavedByLocalPanelInstrument>(); m_componentClassies.emplace_back(componentClassSavedByLocalPanelInstrument); auto componentClassSavedByFarInstrument = std::make_shared<ComponentClassSavedByFarInstrument>(); m_componentClassies.emplace_back(componentClassSavedByFarInstrument); auto componentClassSavedByTracedInstrument = std::make_shared<ComponentClassSavedByTracedInstrument>(); m_componentClassies.emplace_back(componentClassSavedByTracedInstrument);
就是执行的代码一样,类型不一样,于是我在hpp里面写上如下代码:
template <class T> std::shared_ptr<T> generateInstrumentComponent() { std::shared_ptr<T> componentClass = std::make_shared<T>(); return componentClass; }
后面每个改动都直接在这个函数里面改动就行了,每个代码直接改成
auto componentClass = generateInstrumentComponent<ComponentClassSavedByDCS>();
m_componentClassies.emplace_back(componentClass);
就行了,要学会用高级工具!