Created
January 5, 2011 01:52
-
-
Save mfoliveira/765808 to your computer and use it in GitHub Desktop.
Single-variable List Comprehension in C++ using Preprocessor Macros
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
/* Single-variable List Comprehension in C++ using Preprocessor Macros | |
* | |
* (C) Copyright 2011, Mauricio Faria de Oliveira | |
* http://mfoliveira.org | |
* | |
* This program is free software; you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation; either version 2 of the License, or | |
* (at your option) any later version. | |
*/ | |
#include <iostream> | |
#include <list> | |
using namespace std; | |
/* Pointer to Output Set */ | |
typedef void list_comprehension_set; | |
list_comprehension_set *list_comprehension_output_set; | |
/* List-Comprehension Assignment Operator */ | |
template <typename T> | |
void operator << (list<T> &output_set, list_comprehension_set* &output_set_pointer) { | |
/* Store output_set's address for the macro. */ | |
output_set_pointer = (list_comprehension_set *) &output_set; | |
} | |
/* List Comprehension */ | |
#define list_comprehension(output_function, variable, input_set, predicate) \ | |
\ | |
list_comprehension_output_set; \ | |
\ | |
{ \ | |
typeof((input_set).begin()) iterator = (input_set).begin(); \ | |
typeof((input_set).front()) variable = *iterator; \ | |
\ | |
list< typeof(output_function) > *output_set = \ | |
(list< typeof(output_function) > *) list_comprehension_output_set; \ | |
\ | |
for (; \ | |
iterator != (input_set).end(); \ | |
++iterator) \ | |
{ \ | |
variable = *iterator; \ | |
\ | |
if (predicate) \ | |
output_set->push_back(output_function); \ | |
} \ | |
} | |
int main(int argc, char** argv) { | |
/* Input set */ | |
list<int> input; | |
for (int i = 0; i < 5; ++i) | |
input.push_back(i); | |
/* Output set */ | |
list<double> output; | |
/* List Comprehension */ | |
output << list_comprehension(3.1415 * x, x, input, x < 3); | |
/* Input set contents */ | |
for (list<int>::iterator it = input.begin(); | |
it != input.end(); | |
++it) | |
cout << *it << endl; | |
cout << endl; | |
/* Output set contents */ | |
for (list<double>::iterator it = output.begin(); | |
it != output.end(); | |
++it) | |
cout << *it << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment