Menu

Generic QueryValue() Method

Developer
2006-03-01
2013-05-20
  • Steve Hyatt

    Steve Hyatt - 2006-03-01

    Hi.

    I wrote the following snipped that uses tempalates that can get the value of an attribute with one function:

    in TiXmlAttribute:

        #ifdef TIXML_USE_STL
        template <typename DataType>
        int QueryValue(DataType* val) const
        {
            std::stringstream ss(value.c_str());
            if (ss >> *val)
                return TIXML_SUCCESS;
            return TIXML_WRONG_TYPE;
        }
        #endif

    Usage:

    ...
    int intVal;
    float floatVal;

    if (attrib->QueryValue(&intVal) == TIXML_SUCCESS) {
        cout << "int val=" << intVal << endl;
    }

    if (attrib->QueryValue(&floatVal) == TIXML_SUCCESS) {
        cout << "float val=" << floatVal << endl;
    }

    ...

    Would anyone else find this useful?

    Steve

     
    • Ellers

      Ellers - 2006-03-02

      Personally, I'm a fan of templates :)

      Two queries come to mind -

      - is the #ifdef TIXML_USE_STL the right choice? That is, some people (ok, me) might prefer *not* to have STL, but *do* want to have template methods like this. If so, perhaps use #ifdef TIXML_USE_TEMPLATE_EXTRAS or #ifdef TIXML_USE_ADV?

      - is the expression "(ss >> *val)" always going to give a boolean result? Where I say "always" I guess it could mean "for all intents and purposes".

      WDYT?

       
    • Steve Hyatt

      Steve Hyatt - 2006-03-09

      Hi.

      I use the #ifdef since the function uses the STL stringstream class.

      The check for success uses the stream's good() method.  It could be written as:

      int QueryValue(DataType* val) const
      {
          std::stringstream ss(value.c_str());
          ss >> *val;
          if (ss.good()) 
              return TIXML_SUCCESS;
          return TIXML_WRONG_TYPE;
      }

      Thoughts?

      Steve

       
    • Lee Thomason

      Lee Thomason - 2006-03-14

      That's clever.

      We should put that in after a little testing. (Along with Visit() and the memory leak on error fix...) with the next release.

      lee

       
    • Lee Thomason

      Lee Thomason - 2006-03-31

      Implemented - will be checked in to CVS soon.

      Good idea!

      lee

       
    • RJP Computing

      RJP Computing - 2006-04-11

      Is this close to being checked in. I have a great need for that. Thanks

       
    • Lee Thomason

      Lee Thomason - 2006-04-11

      I thought it was, but it's not in CVS. That's a little wierd. I'll check it in tonight.

      lee

       
    • RJP Computing

      RJP Computing - 2006-04-11

      Great! Thanks.

      Ryan

       
    • Lee Thomason

      Lee Thomason - 2006-04-12

      Checked in to CVS, QueryValueAttribute()

      lee

       

Log in to post a comment.