fduff
fduff

Reputation: 3811

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

I have a block of code in which there are multiple times the same kind of operations:

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
}

Pretty sure there's a more elegant way of writing this in modern C++ (11, 17, 20) using templates I assume. Any idea?

Edit: only the VARIABLE_n and VARIABLE_n_TYPE change, params[0] stays as is.

Upvotes: 0

Views: 96

Answers (1)

Caleth
Caleth

Reputation: 62686

Because you want something as both an identifier in code, and as a string literal, you either repeat yourself

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");
    // ...
}

or use a macro

#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

Upvotes: 3

Related Questions