(C++) std::unary\_function
February 24, 2017 · View on GitHub
(C++) std::unary_function
std::unary_function is deprecated [2,3].
std::unary_function is an empty class that serves as the base class of a unary functor. A unary functor defines operator(), where operator() takes one argument.
The advantage of using std::unary_function is its (two) typedefs, so that the derived functors fits into more algorithms. Make functors adaptable [1].
Example: MakeAbs
#include <algorithm> #include <cmath> #include <functional> #include <vector> template <class T> struct Abs : public std::unary_function<T,T> { const T operator()(const T& x) const { return std::abs(x); } }; void MakeAbs(std::vector<int>& v) { std::transform(v.begin(),v.end(),v.begin(),Abs<int>()); }
Example definition of std::unary_function
Simplified from the GNU ISO C++ Library, version 4.7.2:
template<typename _Arg, typename _Result> struct unary_function { typedef _Arg argument_type; typedef _Result result_type; };
References
- Scott Meyers. Effective STL. ISBN: 0-201-74962-9. Item 40: 'Make functor classes adaptable'
- Programming Language C++, Library Working Group. 2010-10-06. Document number: N3145=10-0135
- Working Draft, Standard for Programming Language C++. 2014-08-22. N3936. Paragraph D.8.2. 'The class templates unary_function and binary_function are deprecated. A program shall not declare specializations of these templates.'