C++ sql-like Select example (imperfect)

I just would like to keep it here…

May be there is better implementation? Spent on it 30 mins, have no more time today.

// select.cpp

#include <vector>
#include <iostream>

  template<
      typename OutputCollectionT,
      typename OutputItemT = typename OutputCollectionT::value_type
  >
  class Select {
  public:
      template<
          typename InputCollectionT,
          typename InputItemT = typename InputCollectionT::value_type
      >
      class From {
      public:
          static OutputCollectionT Do(
              const InputCollectionT &Input,
              std::function<OutputItemT(const InputItemT &In)> Selector
          ) {
            OutputCollectionT Out;
            for (const InputItemT &In : Input) {
              Out.push_back(Selector(In));
            }
            return Out;
          }
      };
  };

struct A {
    int P1;
    int P2;
    int P3;
};

struct B {
    int P1;
    int P3;
};

int main() {
  std::vector<A> aa = {
      {1, 2, 3},
      {2, 3, 4},
      {3, 4, 5}
  };

  auto bb = Select<std::vector<B>>::From<std::vector<A>>::Do(
      aa, [=] (const A &a) -> B {
        return { a.P1, a.P3 };
      }
  );

  for (auto &b : bb) {
    std::cout
    << "P1:" << b.P1 << ", "
    << "P3:" << b.P3 << "\n";
  }

  return 0;
}
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *