0

Please explain how someone should reason to deduce the type specifications of the _Func parameter of std::for_each?

Motivation behind the questions is to understand the type requirements from method signature.

template<class _InIt, class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func) {
    _DEBUG_RANGE(_First, _Last);
    _DEBUG_POINTER(_Func);
    _For_each(_Unchecked(_First), _Unchecked(_Last), _Func);

    return (_STD move(_Func));
}
4

4 回答 4

2

This particular signature doesn't say anything about types at all. It's a template which will accept 3 arguments, 2of them being of the same type.

To see what restrictions are imposed on the types of input arguments you should read the implementation of _For_each, which I bet in turn will have two dozens of specialisations and delegations.

Reading STL source code is a sheer nightmare.

So, as suggsted in comments, give it up and go read the documentation.

于 2012-11-06T15:52:14.263 回答
1

Take a look at some documentation, and see the samples.

http://msdn.microsoft.com/en-us/library/e5sk9w9k(v=vs.100).aspx

Essentially, your predicate function should accept a parameter that is the same type as the container::value_type.

std::vector<int> myNumbers;
std::for_each(std::begin(myNumbers), std::end(myNumbers), [](const int number)
{
    // Do something with the number
});
于 2012-11-06T15:52:39.610 回答
0

This is the implementation of std::for_each from libcxx.

template <class _InputIterator, class _Function>
inline _Function
for_each(_InputIterator __first, _InputIterator __last, _Function __f)
{
    for (; __first != __last; ++__first)
        __f(*__first);
    return _VSTD::move(__f);
}

Here's it fairly clear what the "contract" is for _Function. However, this is merely one implementation, and other implementations could more closely follow the standard, or allow other things to work.

于 2012-11-06T15:57:49.003 回答
0

Basically, std::for_each does this:

_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{
  for (; _First < _Last; ++_First)
    _Func(*_First);

  return _Func;
}

So, as you can see, _Func is a function that takes a *_InIt and returns nothing (in fact, it can return whatever, but the return value is discarded). So _Fn1 can be either a pointer to a function taking a *_InIt or a functor whose operator () takes a *_InIt.

Even though the return value of the function, if any, is discarded, if _Fn1 is actually a functor it can have internal state that you can check after executing std::for_each. That's the reason why this algorithm returns _Fn1.

于 2012-11-06T16:01:51.560 回答