[Cs3] Question on Code

Mikhail Nesterenko mikhail at cs.kent.edu
Sun May 4 10:46:28 EDT 2014


> 
> I'm currently looking at one of the examples, and I can't understand it.
> http://vega.cs.kent.edu/~mikhail/classes/cs3.s14/Examples/STL/Algorithms/Functors/bind.cpp
> 
> So in this function, I understand everything up until auto f2.
> The f1 identifier is pretty straight forward, but I don't get how the
> parameters work when using f1 or f2.
> 
> string str = "abc";
> auto f1 = bind(func, _1, str);
> f1(16);
> If I'm understanding it correctly, since you assigned _1 to str, you only
> have to put _1 as a parameter for f1, since str is now implied as a
> parameter.

That is correct. To put another way, bind() creates a function
pointer, that could be used as a callback in STL algorithms, by
modifying the signature of an existing algorithm. In the above example
bind() modifies function func() and creates function f1() that accepts
one parameter (the other parameter of func() is bound to string
"str").

In the below example, f2() accepts two parameters which are the same
parameters as in func() but the order is swapped. 

Now, as an exercise, try to figure out what the types of f1() and f2()
are. That is, try to replace "auto" with the proper type and see if it
compiles. We studied this material in the "metaprogramming" lecture.

Thanks,
--
Mikhail
 
> But f2 is where I get confused.
> auto f2 = bind(func, _2, _1);
> f2("Test", 32);
> 
> I don't understand how you are assigning _2 to something that's already
> been assigned. Even further, why is the first parameter in f2 a string,
> when the first parameter in the void func is an int and not a string?
> 
> If you can clear some of this up for me, I'd really appreciate it.
> Thank you,
> Brendan Gray
> 


More information about the cs3 mailing list