|
![](/i/fill.gif) |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> > You can create anonymous functions. The syntax is:
> >
> > [](int x) { return 2*x; }
> >
> > (Of course that alone won't do anything because you can't call it, as
> > it has no name. However, you can eg. create a variable that represents
> > the function, like: "auto func = [](int x) { return 2*x; };". If you need
> > to eg. return that function from another function, you'll have to use the
> > std::function wrapper. Likewise if you need to give one as parameter to
> > a non-templated or anonymous function.)
> Mmm, interesting.
> So how do you call such a function? Does it just override the usual
> function call notation?
A variable that points to such an anonymous function works like any
function pointer, which means you can call it like a regular function.
Thus if you have, for example:
auto func = [](int x) { return 2*x; };
then you can simply call it like
func(5);
Templates taking a functor as parameter work the same way. You could
have something like:
template<typename T, typename Comparator>
bool compare(const T& value1, const T& value2,
const Comparator& comparatorFunction)
{
return comparatorFunction(value1, value2);
}
In the above example any comparator function will do (a comparator
function is something that behaves like a function taking two parameters
and returns a boolean). This can be a regular function, a functor (a class
that behaves like a function), a lambda, or an object of type std::function.
Thus you can call it eg. like:
compare(1, 3, [](int v1, int v2) { return v1 < v2; })
--
- Warp
Post a reply to this message
|
![](/i/fill.gif) |