一种更优雅的编写重复代码(模板)的方式?

A more elegant way of writing repetitive code (template)?

我有一段代码,其中有多次相同类型的操作:

void fn() {
  if (params[0].count("VARIABLE_1"))
  {
     STRUCT.VARIABLE_1= boost::lexical_cast<VARIABLE_1_TYPE>(params[0].at("VARIABLE_1"));
  }
  if (params[0].count("VARIABLE_2"))
  {
     STRUCT.VARIABLE_2 = boost::lexical_cast<VARIABLE_2_TYPE>(params[0].at("VARIABLE_2"));
  }
  // many times this kind of if (...) with different parameters
}

很确定在现代 C++(11、17、20)中有一种更优雅的方式使用我假设的模板来编写它。有什么想法吗?

编辑:只有VARIABLE_nVARIABLE_n_TYPE改变,params[0]保持原样。

因为你想要一些东西既作为代码中的标识符,又作为字符串文字,你要么重复自己

template<typename T, typename Map>
void extract_param(T & t, const Map & map, std::string name) {
    if (auto it = params.find(name); it != params.end()) {
        t = boost::lexical_cast<T>(*it);
    }
}

void fn() {
    extract_param(STRUCT.VARIABLE, params[0], "VARIABLE");
    // ...
}

或使用宏

#define EXTRACT_PARAM(Key) if (auto it = params[0].find(#Key); it != params[0].end()) { \
    STRUCT.Key = boost::lexical_cast<decltype(STRUCT.Key)>(*it); \
}

void fn() {
    EXTRACT_PARAM(VARIABLE)
    // ...
}

#UNDEF EXTRACT_PARAM