fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4.  
  5. namespace detail
  6. {
  7. using std::begin;
  8. using std::end;
  9.  
  10. template <typename Container, typename F>
  11. auto RetrieveTransformation(const Container& c, F f)
  12. -> std::vector<std::decay_t<decltype(f(*begin(c)))>>
  13. {
  14. // if `F` return `const T&`, we want `std::vector<T>`,
  15. // so we remove reference and cv qualifier with `decay_t`.
  16. //
  17. // That handles additionally the case of lambda
  18. // The return type of lambda [](const std::string&s) { return s;}
  19. // - is `const std::string` for msvc
  20. // - is `std::string` for for gcc
  21. // (Note that the return type rules have changed:
  22. // see http://w...content-available-to-author-only...d.org/jtc1/sc22/wg21/docs/cwg_defects.html#1048)
  23. using F_Ret = std::decay_t<decltype(f(*begin(c)))>;
  24. std::vector<F_Ret> res;
  25. res.reserve(std::distance(begin(c), end(c)));
  26. for (const auto& e : c)
  27. {
  28. res.push_back(f(e));
  29. }
  30. return res;
  31. }
  32.  
  33. }
  34.  
  35. template <typename Container, typename F>
  36. auto RetrieveTransformation(const Container& c, F f)
  37. -> decltype(detail::RetrieveTransformation(c, f))
  38. {
  39. return detail::RetrieveTransformation(c, f);
  40. }
  41.  
  42. struct A
  43. {
  44. int color;
  45.  
  46. A(int p_f) : color(p_f) {}
  47.  
  48. int getColor() const { return color; }
  49. };
  50.  
  51. int main ()
  52. {
  53. A la[4] = {A(3),A(5),A(2),A(1)};
  54. std::vector<int> lv = RetrieveTransformation(la, std::mem_fn(&A::getColor));
  55. for (const auto& e : lv) std::cout << ' ' << e;
  56. std::cout << std::endl;
  57. for (const auto& e : RetrieveTransformation(la, [](const A&a){return a.color;})) std::cout << ' ' << e;
  58. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
 3 5 2 1
 3 5 2 1