Last active
March 23, 2019 10:51
-
-
Save y-fedorov/ce75f158e7338fd237942f78cb9fb9be to your computer and use it in GitHub Desktop.
std::bind example
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> | |
// Example from Jason Turner's video. | |
// https://youtu.be/JtUZmkvroKg?t=290 | |
void print(int i, const std::string_view s) { | |
std::cout << i << ' ' << s << '\n'; | |
} | |
int main() { | |
int i = 10; | |
const auto myFunc = std::bind(&print, std::ref(i), std::placeholders::_1); | |
myFunc("Hello"); | |
i = 42; | |
myFunc("Hi"); | |
return 0; | |
} | |
/* | |
output: | |
10 Hello | |
42 Hi | |
*/ |
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> | |
// Example from Jason Turner's video. | |
// https://youtu.be/JtUZmkvroKg?t=290 | |
void print(int i, const std::string_view s) { | |
std::cout << i << ' ' << s << '\n'; | |
} | |
int main() { | |
// re-order function parameters | |
const auto myFunc = std::bind(&print, std::placeholders::_2, std::placeholders::_1); | |
myFunc("Hello", 10); | |
myFunc("Hi", 42); | |
return 0; | |
} | |
/* | |
output: | |
10 Hello | |
42 Hi | |
*/ |
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
// Example from Jason Turner's video. | |
// https://youtu.be/JtUZmkvroKg?t=290 | |
template <typename T> | |
void print(T i, const std::string_view s) { | |
std::cout << i << ' ' << s << '\n'; | |
} | |
int main() { | |
// re-order function parameters | |
const auto myFunc = std::bind(&print<int>, std::placeholders::_2, std::placeholders::_1); | |
myFunc("Hello", 10); | |
myFunc("Hi", 42); | |
return 0; | |
} | |
/* | |
output: | |
10 Hello | |
42 Hi | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment