Implementation suggestions for creating an expression later used to evaluate the contents of a map in c++?

我是研究僧i 提交于 2019-12-12 01:35:52

问题


My goal is to create a "validator" object for maps. An example of how I'd like to use it:

MyValidator my_validator = (IsEmpty("key name 1") && DoesExist("key name 2"))
                           || HasNElements("key name 3", num)

Later:

if(my_validator.validate(some_map)) {
// do something
}

In this case, my_validator.validate(some_map) would return true if some_map["key name 1"] was empty and some_map["key name 2"] exists, or if some_map["key name 3"] had 3 elements.

Any implementation suggestions would be appreciated.

See this post for my prior question regarding an implementation I was attempting: How do I create overloaded operators for boost pointers in C++?


回答1:


Using that expression syntax is going to make it very difficult. The way I've always done this in the past is to have an abstract Rule class from which I derive concrete rule types. I then add these to the validator:

Validator v;
v.add( new NotValueRule( "foo" ) );
v.add( new NotIntRule ) );
v.add( new BetweenRule( "a", "z" ) );

and then call the validate() function on the validator. This doesn't allow directly for ands and ors, but you can get round that with a couple of "fake" rules called AndRule and OrRule.




回答2:


It sounds like what you want is generally called a Lambda. For now, you could look up Boost::lambda. In C++0x, lambda expressions will be directly supported by the language.



来源:https://stackoverflow.com/questions/3441608/implementation-suggestions-for-creating-an-expression-later-used-to-evaluate-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!