📜 ⬆️ ⬇️

Property in C ++ (with access by name, but without setters)

Another Property option that I actually used in my work was to pass command line parameters to the program. Has no flexibility in the types used, but for this task was very convenient.

DISCLAIMER: do not try to apply this pattern in cycles and environments with a lack of resources — a read-write cycle of one parameter takes 2-5 microseconds, with a large number of parameters.

In the follow-up to Property in C ++ to C ++
')

#include <string> #include <map> #include <iostream> using namespace std; class PropertyVariant { enum Type{ Null, Integer, String }; int ivalue; string svalue; Type type; public: PropertyVariant() { type = Null; } PropertyVariant(const PropertyVariant &clone) { type = clone.type; ivalue = clone.ivalue; svalue = clone.svalue; } PropertyVariant( int val ) { type = Integer; ivalue = val; } PropertyVariant( const string &val ) { type = String; svalue = val; } PropertyVariant( const char *val ) { type = String; svalue = val; } operator int() { if( type != Integer ) throw runtime_error( "wrong type" ); return ivalue; } operator string() { if( type != String ) throw runtime_error( "wrong type" ); return svalue; } }; int main() { map<string,PropertyVariant> variant_props; variant_props["Integer"] = 100; variant_props["String"] = "crazy_dev"; string s = variant_props["String"]; int i = variant_props["Integer"]; return 0; } 

Source: https://habr.com/ru/post/125941/


All Articles