Skip to content

Instantly share code, notes, and snippets.

@sandeepkumar-skb
Created September 1, 2020 05:00
Show Gist options
  • Save sandeepkumar-skb/2acf3e3de3c8a5cf18911e53a3b89e69 to your computer and use it in GitHub Desktop.
Save sandeepkumar-skb/2acf3e3de3c8a5cf18911e53a3b89e69 to your computer and use it in GitHub Desktop.
C++ bind working
#include <iostream>
void print(int& i){
std::cout << i << "\n";
}
int main(){
int i = 10;
// Binding function print
auto foo = std::bind(&print, i);
std::cout << "Calling bind-print: " ;
foo();
i = 30;
std::cout << "Calling bind-print: ";
foo();
// Output of the bind didn't change even though we changed the value of i
// To resolve this we can use std::ref(i) and pass that to bind
auto bar = std::bind(&print, std::ref(i));
std::cout << "Calling bind-print with std::ref input: ";
bar();
i = 20;
std::cout << "Calling bind-print with std::ref input: ";
bar();
// Bind can swallow all the arguments which are passed to it.
auto baz = std::bind(&print, std::ref(i));
std::cout << "bind func can swallow all the extra arguments passed to it without complaining" << std::endl;
std::cout << "baz(10,20,30,40): ";
baz(10,20,30,40);
return 1;
}
@sandeepkumar-skb
Copy link
Author

Compile: g++ bind.cpp -std=c++14 -o bind
Execute: ./bind

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment