Last active
December 25, 2015 20:10
-
-
Save markzyu/0b6fa03e830011c6e58c to your computer and use it in GitHub Desktop.
Testing C++11 functional
This file contains 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> | |
#include <string> | |
#include <functional> | |
using namespace std; | |
class TestScope | |
{ | |
public: | |
int val; | |
TestScope() | |
{ | |
val=0; | |
} | |
TestScope(int a) | |
{ | |
val=a; | |
} | |
~TestScope() | |
{ | |
cout<<"Destroying!!!"<<endl; | |
} | |
TestScope& operator=(int a) | |
{ | |
val=a; | |
return *this; | |
} | |
void test() | |
{ | |
cout<<val; | |
} | |
}; | |
int main() | |
{ | |
// Test recursive | |
// use '&' to pass 'fibo' as reference. | |
function<int (int)> fibo = [&](int n) -> int { | |
if(n==1 || n==2) | |
return 1; | |
return fibo(n-1)+fibo(n-2); | |
}; | |
cout<<fibo(8)<<endl; | |
function<void()> tfunc; | |
{ | |
TestScope test = 100; | |
// Test passing by reference | |
tfunc = [&]() { | |
cout<< "test = "; | |
test.test(); | |
cout<<endl; | |
}; | |
test = 10000; | |
tfunc(); | |
} | |
// Test out of scope (this is the only test that fails) | |
tfunc(); | |
return 0; | |
} | |
/* Result: | |
21 | |
test = 10000 | |
Destroying!!! | |
test = 10000 | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment