Jump to content

  • Log In with Google      Sign In   
  • Create Account

We need your feedback on a survey! Each completed response supports our community and gives you a chance to win a $25 Amazon gift card!


#ActualSiCrane

Posted 17 February 2014 - 12:44 AM

This looks like a job for pointer to members:

template <typename T, typename U, typename Container>
T SumValuesFrom(Container c, T U::* member_ptr) {
  return std::accumulate(c.begin(), 
                         c.end(), 
                         T(), 
                         [=](T a, const U & b) {
                           return a + (b.*member_ptr);
                         });
}

int main(int, char **) {
  std::vector<MyStruct> myContainer = /* */;
  int total = SumValuesFrom(myContainer, &MyStruct::memberVariable);
}

#1SiCrane

Posted 17 February 2014 - 12:11 AM

This looks like a job for pointer to members:
template <typename T, typename U, typename Container>
T SumValuesFrom(Container c, T U::* member_ptr) {
  return std::accumulate(c.begin(), 
                         c.end(), 
                         T(), 
                         [=](T a, const MyStruct & b) {
                           return a + (b.*member_ptr);
                         });
}

int main(int, char **) {
  std::vector<MyStruct> myContainer = /* */;
  int total = SumValuesFrom(myContainer, &MyStruct::memberVariable);
}

PARTNERS