samedi 31 décembre 2016

C++ Repeated do-if-do pattern

I currently have code of the following form:

Do1(A);
if (B != null) Do1(B);

Do2(A, true);
if (B != null) Do2(B, true);

Do3(A);
if (B != null) Do3(B);

So several times, I execute something for object A, and if B is specified, I also do it for B. This means my entire code is duplicated and I would like to change that but I can't come up with a good way to improve this pattern.

The only idea I had so far was something like

auto doBoth = [&A,&B](function<void(const T&)> f) {
  f(A);
  if (B != null) f(B);
};

doBoth(&Do1);
auto do2_bind = [](const T& obj) {Do2(obj, true);};
doBoth(do2_bind);
doBoth(&Do3);

but I feel like that would greatly reduce readability and make it harder for someone to understand my code, as there is this quite abstract lambda function and a lot of lambdas in general.

Aucun commentaire:

Enregistrer un commentaire