But passing function has shortcomings 1) Can’t be inline. 2) sometimes
It can’t be compile due to different compiler implementation. 3)
You can’t adapt or custom it. So STL invented a functor(function
object). It is class or structure objects for which the () operator is
overloaded.
You can use struct or class. If you want to have a private customized value,
you have to use class to build a functor. Such as cutoff value in below code.
In previous example, you can see advantage of usage less_than_value.
You can inherit from template unary_function when you declare
a functor, then you functor is adaptable by std::not1.
you can change value when you build a less_than_value functor.
set or map are template class. So it only accept type, not function, If
you want to give set or map a customized compare function, you have
to use functor to define a type.
Based on previous example, I would like to say something about type,variable, expression, value.
type is build-in type, custom type(class, struct), and pointer,
reference type.
variable has a name and value,
expression has no name but has value,
value can be divided by three categories, can overload move ctor.
template function is a function, we have to input value, so we pass variable
or expression. in previous example, yanCompare() produce a obj
variable.
template container need type. so we have to input type, so we input
yanCompare, It’s a class type.
Given a variable or expression, we need to know its type, we can use auto,
T in template and decltype. detail can be seen "type inference"
section.
Given a container, we can get value_type by predefined type information in
container.
given a type, we need to define an variable, we can use typedef or using alias
to replace complex type in C++(such as: vect<pair<string, int> >). In
template,
In template class, If you define depended type, use using alias, detail can be
seen in using alias part in the last chapter.
Sometimes, you don’t want to reuse this functor which will cause you write
clutter code, so C++14 introduce lambda. Detail can be seen in C++ 11
New features.