Property Klassen Probleme (implizit casten)



  • Hallo.

    Ich versuch mich gerade selbst an einer möglichst eleganten Property Klasse. Nachdem ich endlich meine Faulheit überwunden habe und anfange mich in die diversen boost-libs einzuarbeiten, hab ich natürlich boost::any entdeckt.

    class Property
    {
       public: //Ctors
           Property();
           Property(std::string name,const boost::any &value);
           Property(const Property &other);
    
           std::string Name;
           boost::any Value;
    
           //diverse schon implementierte operatoren lass ich jetzt mal außen vor
    };
    

    Ich möchte so Etwas vermeiden:

    if(myProperty.Value.type() == typeid(int))
            int a = boost::any_cast<int>(myProperty.Value);
    

    und etwa so Etwas daraus machen

    int a = myProperty; //ohne static_cast<int>myProperty;
    
      //Alternativ
      int b = myProperty.Value; //myProperty.Value() ?
    

    oder zumindest eine elegantere Lösung finden.

    Habt ihr da Vorschläge?



  • TravisG schrieb:

    Ich möchte so Etwas vermeiden:

    if(myProperty.Value.type() == typeid(int))
            int 5 = boost::any_cast<int>(myProperty.Value);
    

    und etwa so Etwas daraus machen

    int 5 = myProperty; //ohne static_cast<int>myProperty;
    
      //Alternativ
      int 5 = myProperty.Value; //myProperty.Value() ?
    

    oder zumindest eine elegantere Lösung finden.

    Habt ihr da Vorschläge?

    Du willst 5 einen anderen Wert zuweisen?



  • wenn du in wirklichkeit gar nicht boost::any , sondern boost::variant brauchst, dann geht das.

    ansonsten vielleicht so

    class Property
    {
    public:
       template <class T>
       operator T ()
       {
          return any_cast<T> (property);
       }
    };
    
    Property prop("foo", 42);
    int i = prop;
    

    davon würde ich allerdings abraten, verhält sich nämlich nicht immer so, wie gewünscht.

    cout << prop << endl; //Fehler!
    

    mit boost::variant sollte das theoretisch auch funktionieren (weiß allerdings nicht, ob es tatsächlich klappt, hab nur einmal selbst ein variant implementiert, das das kann)



  • nixversteher2.0 schrieb:

    TravisG schrieb:

    Ich möchte so Etwas vermeiden:

    if(myProperty.Value.type() == typeid(int))
            int 5 = boost::any_cast<int>(myProperty.Value);
    

    und etwa so Etwas daraus machen

    int 5 = myProperty; //ohne static_cast<int>myProperty;
    
      //Alternativ
      int 5 = myProperty.Value; //myProperty.Value() ?
    

    oder zumindest eine elegantere Lösung finden.

    Habt ihr da Vorschläge?

    Du willst 5 einen anderen Wert zuweisen?

    oops, das kommt vom schnellen schreiben. ist editiert.



  • wie wäre es mit std::pair? ich sehe da grad nicht den Sinn deiner Klasse.


Anmelden zum Antworten