我不认为这是一个好主意。我更喜欢编写两个不同的函数来处理两种不同的类型,如下所示:
// Also, note, your function is very similar to
// std::accumulate from numeric header
std::vector<Foo> v1{3.14159, 1.77245385};
std::accumulate
(
v1.begin(), v1.end(), 0.,
[] (double i, const Foo& f) { return i + f(); }
);
std::vector<double> v2{3.14159, 1.77245385};
std::accumulate(v2.begin(), v2.end(), 0.);
但如果你不想这样做,我建议编写一个函数包装器:
namespace detail
{
template <class F, class V, class T>
auto function_wrapper(F&& f, V&& v, T&& t)
-> typename std::enable_if
<
std::is_class<typename std::remove_reference<T>::type>::value,
typename std::remove_reference<V>::type
>::type
{
return std::forward<F>(f)(std::forward<V>(v), std::forward<T>(t)());
}
template <class F, class V, class T>
auto function_wrapper(F&& f, V&& v, T&& t)
-> typename std::enable_if
<
!std::is_class<typename std::remove_reference<T>::type>::value,
typename std::remove_reference<V>::type
>::type
{
return std::forward<F>(f)(std::forward<V>(v), std::forward<T>(t));
}
} // namespace detail
template < class _InIt,
class _Ty,
class _Fn2 > inline
_Ty accumulateSimplePtr(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)
{
for (; _First != _Last; ++_First)
_Val = detail::function_wrapper(_Func, _Val, *_First);
return (_Val);
}
class Foo
{
public:
Foo(double d): _d(d)
{
}
double operator() () const
{
return _d;
}
private:
double _d;
};
int main()
{
auto f = [] (double a, double b) { return a + b; };
std::vector<Foo> v1{3.14159, 1.77245385};
std::cout << accumulateSimplePtr(v1.begin(), v1.end(), 0., f) << std::endl;
std::vector<double> v2{3.14159, 1.77245385};
std::cout << accumulateSimplePtr(v2.begin(), v2.end(), 0., f) << std::endl;
return 0;
}