Just wrote this. I wanted a way to add values from a member-variable of each element in a function.
struct MyStruct
{
std::string otherData;
int memberVariable;
};
std::vector<MyStruct> myContainer = {...};
//Sum the values of *a member variable* within each element of a container.
int total = SumValuesFrom(myContainer, memberVariable);
Note that 'memberVariable' isn't a variable. Or a variable type. Also note that it is 11:23 PM my time, and I got zero sleep last night.
So naturally, I'm at peak programming performance.
Here's my functional, reusable, perfectly abusive of macros solution:
#define SumValuesFrom(container, member) priv_XValuesFrom_normal(container, member, [](const decltype(container.front().member) &valueA, const decltype(container.front().member) &valueB) { return (valueA + valueB); })
#define priv_XValuesFrom_normal(container, member, addingFunctor) priv_XValuesFrom<decltype(container.front().member)>(container, [](const decltype(container)::value_type &element) { return element.member; }, addingFunctor)
template<typename ValueType, typename ContainerType, typename ReadingFunctor, typename AddingFunctor>
ValueType priv_XValuesFrom(const ContainerType &container, ReadingFunctor getValue, AddingFunctor addValues, ValueType initialValue = ValueType())
{
ValueType total = initialValue;
for(const auto &element : container)
{
total = addValues(total, getValue(element));
}
return total;
}
There's even a version for if the elements are pointers (haven't tested that yet).
It compiles and runs: [Ideone.com]
The only thing my sleep-deprived mind is displeased with is the dependency on container.front().