Created
June 28, 2015 17:17
-
-
Save krysseltillada/d865f716ec505eef2e47 to your computer and use it in GitHub Desktop.
function pointers (exercise)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| /// function pointers | |
| double sample_func (double d1, double d2) | |
| { | |
| std::cout << __func__ << " was called "; | |
| } | |
| int add (int n1, int n2) | |
| { | |
| std::cout << __func__ << " is called that has int parameter" << std::endl; | |
| return n1 + n2; | |
| } | |
| double add (double d1, double d2) | |
| { | |
| std::cout << __func__ << " is called that has double parameter" << std::endl; | |
| return d1 + d2; | |
| } | |
| int (*ptr_add)(int, int) = add; /// or ptr_add = add || ptr_add = &add; | |
| /// function overload pointers | |
| double (*pof)(double, double) = add; /// needs to be exact so pof is a pointer to a function that have parameters of two double and returns int which is int add (double d1, double d2) | |
| /// function pointer parameters | |
| double f1_mimic(double d1, double d2, double (*m)(double, double)) | |
| { | |
| return m(d1, d2); | |
| } | |
| /// function pointer parameters with type alias typedef | |
| typedef int (*tf)(int, int); /// equivalent to typedef int tf(int, int); | |
| int f2_mimic(int i1, int i2, tf f) | |
| { | |
| return f(i1, i2); | |
| } | |
| /// function pointer parameters with decltype and typedef | |
| typedef decltype(sample_func) d_ptr; /// equivalent to typedef decltype(sample_func) *d_ptr; | |
| double f3_mimic (double d1, double d2, d_ptr dp) | |
| { | |
| return dp(d1, d2); | |
| } | |
| int main() | |
| { | |
| std::cout << add(2, 2) << std::endl | |
| << ptr_add(4, 4) << std::endl | |
| << (*ptr_add)(10, 10) << std::endl; | |
| std::cout << pof (2.3, 2.4) << std::endl | |
| << add (2.3, 2.65) << std::endl; | |
| std::cout << f1_mimic(2.3, 2.4, add); | |
| std::cout << f2_mimic(200, 200, add); | |
| std::cout << f3_mimic(420, 420, add); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment