Created
March 20, 2013 14:14
-
-
Save waffle2k/5204974 to your computer and use it in GitHub Desktop.
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
// Compile with: | |
// | |
// g++ -W -Wall -Wextra -pedantic -std=c++0x closure.cpp -o closure | |
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <utility> | |
#include <memory> | |
#include <initializer_list> | |
class Container { | |
private: | |
std::vector<int> *_v; | |
public: | |
const std::vector< int > & operator()( const int & ref ){ | |
if( ref % 2 == 0 ){ | |
(*_v).push_back( ref ); | |
} | |
return *_v; | |
}; | |
const std::vector< int > & operator()(){ | |
return (*_v); | |
}; | |
Container() : _v( new std::vector<int> ) { | |
}; | |
virtual ~Container(){ | |
// Yes, this is an intentional memory leak for | |
// sake of brevity | |
} | |
}; | |
int main( void ){ | |
Container *visitor = new Container(); | |
auto array = { | |
1,2,3, | |
4,5,6, | |
7,8,9, | |
10,11,12, | |
13,14,15, | |
16,17,18 | |
}; | |
// Add all even elements to the closure "visitor" | |
std::for_each( array.begin(), array.end(), *visitor ); | |
// Print them out, using lambda functions | |
std::for_each( (*visitor)().begin(), (*visitor)().end(), []( const int & ref ){ | |
std::cout << ref << std::endl; | |
}); | |
delete visitor; | |
return 0; | |
} |
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
#!/usr/bin/perl -w | |
use strict; | |
sub closure { | |
my @a; | |
return ( sub { | |
my $v = shift; | |
push( @a, $v ) | |
if $v % 2 == 0 and ( $v =~ /^\d+$/ ); | |
}, \@a ); | |
} | |
my ($visitor, $aref) = closure(); | |
&$visitor($_) for 1..18; | |
print join( "\n", @$aref ),"\n"; |
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
closure: closure.cpp | |
g++ -W -Wall -Wextra -pedantic -std=c++0x closure.cpp -o closure | |
clean: | |
rm closure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment