Skip to content

Instantly share code, notes, and snippets.

@markzyu
Last active December 25, 2015 20:10
Show Gist options
  • Save markzyu/0b6fa03e830011c6e58c to your computer and use it in GitHub Desktop.
Save markzyu/0b6fa03e830011c6e58c to your computer and use it in GitHub Desktop.
Testing C++11 functional
#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