Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Last active March 23, 2019 10:51
Show Gist options
  • Save y-fedorov/ce75f158e7338fd237942f78cb9fb9be to your computer and use it in GitHub Desktop.
Save y-fedorov/ce75f158e7338fd237942f78cb9fb9be to your computer and use it in GitHub Desktop.
std::bind example
#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
*/
#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
*/
// 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