Reputation: 5666
Consider this function, which is supposed to multiply each number in a range by a supplied value, and optionally take in a functor to get a reference to the number to be multiplied:
template <typename TIter, typename TNumber, typename TTransformer = self_reference<iterator_traits<TIter>::value_type>>
void multiply_range(TIter begin, TIter end, TNumber multiplicand, TTransformer transformer = TTransformer()) {
for_each(begin, end, [multiplicand, &transformer](typename iterator_traits<TIter>::value_type val){
transformer(val) *= multiplicand;
}
}
Is there something in the standard library that does what self_reference
is trying to do, i.e. a functor that returns a reference to its input parameter?
(The standard library has things like std::less
and std::plus
, but am I not asking for something even more basic?)
So, the following code should work:
int x[4] = {1, 3, 5, 7};
multiply_range(x, x + 4, 2);
// x will become {2, 6, 10, 14}
vector<int> y[2] = {{1, 2}, {3, 4, 5}};
multiply_range(y, y + 2, 2, [](vector<int>& v) -> int& { return v[0]; });
// y will become {{2, 2}, {6, 4, 5}}
C++11 and C++14 are fine too.
Upvotes: 3
Views: 184
Reputation: 15673
a functor that returns a reference to its input parameter
is quite different from a
C++ Functor that Returns Itself
What you're looking for is most commonly known as the "identity" transform(er, or functor), and is not part of the C++ standard library.
Upvotes: 4