Created
July 4, 2012 01:16
-
-
Save geovanisouza92/3044546 to your computer and use it in GitHub Desktop.
Delegates para validação automágica
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 <vector> | |
#include <typeinfo> | |
#include <sstream> | |
using namespace std; | |
namespace Validation | |
{ | |
namespace ValidationStatus | |
{ | |
enum EStatus | |
{ | |
Failed = -1, | |
Success = 0, | |
Ignored = 1 | |
}; | |
} | |
struct ValidationResult | |
{ | |
ValidationStatus::EStatus status; | |
string reason; | |
}; | |
class Element { }; | |
typedef ValidationResult (*ValidationFunction)(const Element &); | |
typedef void (*Block)(const vector<ValidationFunction>::iterator &); | |
class Validator: public vector<ValidationFunction> | |
{ | |
public: | |
Validator & | |
operator+=(const ValidationFunction & func) | |
{ | |
this->push_back(func); | |
return *this; | |
} | |
void | |
each(const Block & block) | |
{ | |
for (auto elem = this->begin(); elem < this->end(); elem++) | |
block(elem); | |
} | |
}; | |
} | |
Validation::ValidationResult foo(const Validation::Element & e) | |
{ | |
return {Validation::ValidationStatus::Failed, "Falhou"}; | |
} | |
Validation::ValidationResult bar(const Validation::Element & e) | |
{ | |
return {Validation::ValidationStatus::Ignored, "Ignorado"}; | |
} | |
Validation::ValidationResult baz(const Validation::Element & e) | |
{ | |
return {Validation::ValidationStatus::Success, "Sucesso"}; | |
} | |
namespace Validation | |
{ | |
static Validation::Validator validator; | |
} | |
Validation::Validator & | |
getValidator() { | |
return Validation::validator; | |
} | |
int main() | |
{ | |
getValidator() += foo; | |
getValidator() += bar; | |
getValidator() += baz; | |
for (auto i = 0; i < 10; i++) | |
getValidator() += [] (const Validation::Element & e) -> Validation::ValidationResult { | |
static int j; j >= 0 ? ++j : j; stringstream s; s << "Lambda #"; s << j; | |
return {Validation::ValidationStatus::Success, s.str() }; | |
}; | |
getValidator().each([] (const Validation::Validator::iterator & it) { | |
cout << (*it)(Validation::Element()).reason << endl; | |
}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment