Created
September 1, 2020 05:00
-
-
Save sandeepkumar-skb/2acf3e3de3c8a5cf18911e53a3b89e69 to your computer and use it in GitHub Desktop.
C++ bind working
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> | |
| 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile:
g++ bind.cpp -std=c++14 -o bindExecute:
./bind