Functions Flashcards
How do you declare a function pointer?
<return type> (*<ptr_fun>)(args type...)
for example:
int (p_fun)(const char)
How do you decalre a pointer function as a porperty in a class?
class A { void (*ptr_f)(const char*); public: A(void (*func)(const char*)):ptr_f{func}{} void raise_func(const char* s) { if(ptr_f) ptr_f(s); } };
What is a **Functor*?
It’s an Object that is used as a function which overrides the operato () to invoke several functions like:
~~~
class A{
public:
int operator()(int x, int y){ return x+y;}
void operator()(const char* name){ cout «_space;“Hello “ «_space;name; }
};
~~~
What is the syntaxis to declare a lambda?
auto <lmb_name> = [<captures>](<args>) mutable noexpect -><return tuype> { <Body> return <value>; };
In lambda function, what is the function of mutable
keyword?
It allows to modify the variables that were capture by copy.
What is a functor?
Son objetos que se utilizan como funciones, reescribiendo el operador operator()
How do you write a functor which returns a bool value from a comparation of two integers?
class Comparator { public: bool operator()(int a, intb){return a==b;} }
What does std::bind
do and what is its header file?
From <functional>
It create a wrapper arround a function and, the wraper, can be used in several context to call the function
Having the next function:
int fx(int y, string s)
How do you create a wrapper, using std::bind
.
#include<functional> using namespace std; using namespace std::placeholders; int fx(int x, string s) { cout << s << "\n"; return x*10; } int main() { auto f = std::bind(fx, _1, _2); cout << "result " << f(23, "Hello"); return 0; }
Output:
~~~
result Hello
230
~~~
What will be the output of this code and why?
~~~
int fx(int x, int y, string id, int z)
{
cout «_space;”[” «_space;id «_space;”] “;
cout «“x: “ «_space;x «_space;”; y: “ «_space;y «_space;”; z: “ «_space;z «_space;“\n”;
return x*10;
}
int main()
{
auto f = std::bind(fx, _2, _4, “MyId”, _1);
cout «_space;“result “ «_space;f(1, 23, “MyOther”, 55);
return 0;
}
~~~
result [MyId] x: 23; y: 55; z: 1 230
Because you are declaring the bind as std::bind(fx, x, y, s, z) but at the same time you are mapping the parameter with the placeholders
as:
~~~
f( x, y, s, z)
f( 1, 23, “MyOther”, 55)
bind(fx, _2, _4, “MyId”, _1)
~~~
which means that:
+ x, for fx, will be taken from the second parameter (_2) of bind (23).
+ y, for fx, will be taken from the fourth parameter (_4) of bind (55).
+ z, for fx, will be taken from the second parameter (_1) of bind (1).
+ s always will be “MyId” because it was declared as a constant on the bind.
What kind of object is retuned by std::bind
?
std::function
which is the wrapper of the function that must declare the protptype of the function
Function: int fx(int x, int y, string id, int z)
Declaration: std::function<int(int,int,string,int)>