vendredi 13 août 2021

Is it possible to use C++ macros to generate blocks of code?

I have a C++ program where a certain pattern of blocks of code keeps repeating, and I am wondering if I can use C++ MACROS for the preprocessor to auto-generate this code. To be more precise I have blocks of code which look something like this:

for(std::size_t i=0;i< lc_.size(); i++)
{
  std::string str;
  state::MsData lc = data->lc(i);
  convert<data::ClassForLC>(lc.data(), str);
  lc_[i] = data::ClassForLC(str);
}

I then may have another block that looks like this:

for(std::size_t i=0;i< mmop_.size(); i++)
{
  std::string str;
  state::MvData mmop = data->mmop(i);
  convert<data::ClassForMMOP>(mmop.data(), str);
  mmop_[i] = data::ClassForMMOP(str);
}

As you can see the general pattern is something like this:

  for(std::size_t i=0;i< X_.size(); i++)
    {
      std::string str;
      Y X = data->X(i);
      convert<Z>(X.data(), str);
      X_[i] = Z(str);
    }

I was wondering if it is possible to define a macro REPLACE(X,Y,Z) which replaces X,Y,Z in the code above with whatever text I pass as parameter? Note: I use C++11. Thanks

Aucun commentaire:

Enregistrer un commentaire