Using late-binding with STL classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Xx r3negade
    New Member
    • Apr 2008
    • 39

    Using late-binding with STL classes

    I have a function, which reads input from a file and appends each line of the file to an STL object. I want to use this function with both lists and vectors. Since both of these objects have the push_back method, I thought I'd make a common function that can be used by both. Is there any practical way to do this?

    Function show below:

    Code:
    template<class container>
    // The second argument here must be a list, vector, or any other STL object with a push_back() method
    void fileToContainer(const char* fName, container* vecptr) {
        // Open a file and add each line to the list, vector, etc.
        ifstream f(fName);
        string line;
    
        if (f.is_open()) {
            while (! f.eof()) {
                getline(f, line);
                if (line != "") {
                    try {
                        vecptr.push_back(line);
                    }
                    catch (...) {
                        throw ios_base::failure("Invalid container object");
                    }
                }
            }
        }
        else {
            throw ios_base::failure("Could not open " + static_cast<string>(fName));
        }
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Originally posted by Xx r3negade
    I thought I'd make a common function that can be used by both. Is there any practical way to do this?
    Is there something wrong with the function you have there? It seems like you have already done this.

    Comment

    • Xx r3negade
      New Member
      • Apr 2008
      • 39

      #3
      I get this compile error

      error: request for member ‘push_back’ in ‘vecptr’, which is of non-class type ‘std::vector'

      Note that "vector" is the type passed to the function, in a different part of the code.

      Edit: The function call looks like this:
      Code:
      fileToContainer<vector<string> >(argv[1], &ph.puzGrid);
      ph.puzGrid being a vector<string>, of course.

      Comment

      • Xx r3negade
        New Member
        • Apr 2008
        • 39

        #4
        Any help please? Still not quite sure what to do...

        Comment

        • boxfish
          Recognized Expert Contributor
          • Mar 2008
          • 469

          #5
          Code:
          vecptr.push_back(line);
          You can't use the push_back function on vecptr, because it is a pointer to a vector, not an actual vector. You have to dereference it first or use the arrow operator. Try:
          Code:
          vecptr->push_back(line);
          Hope this helps.

          Comment

          • Xx r3negade
            New Member
            • Apr 2008
            • 39

            #6
            *facepalm*
            thanks :D

            Comment

            Working...