0

Here's the situation:

I have a Graph class written in C++ and I need to build Graph objects from Files. The problem is that Graph are memorized in files in a lot of different ways, so I was thinking about a function that, using the file extension, could invoke the correct procedure for building a Graph in a certain format. How should I proceed? Am I wrong or I can't just overload operator>> in my class?Thanks in advance.

manlio
  • 18,345
  • 14
  • 76
  • 126
amon880
  • 35
  • 4
  • See if this post helps http://stackoverflow.com/questions/51949/how-to-get-file-extension-from-string-in-c – kjh Jun 30 '14 at 16:03

2 Answers2

1

operator>> is (should be) agnostic to any details of the stream from which it is extracting, so using this operator is probably the wrong tact.

The best way to do this would be:

graph_type load_from_file(const std::string& file_path) { //or use something like boost::filesystem::path

    std::ofstream file { file_path };

    if(endswith(file_path, ".graph") {
        return deserialize_from_graph(ofstream);
    }
    if(endswith(file_path, ".g2") {
        return deserialize_from_g2(ofstream);
    }
    //other formats here


    //else throw
}

note, endswith is not from the standard library, boost however has an implementation in it's string algorithms.

111111
  • 15,686
  • 6
  • 47
  • 62
0

How do you determine how the data is memorized. If it is just the extension, all you need is a map std::stringpointer_to_function. If the same extension can have several different representations, distinguished, for example, by the first couple of bytes in the file, or information in some common header, you'll have to differ the final choice until you've read these bytes—again, a map to the a pointer to function will do the trick.

Depending on the complexity of the formats to read, you may want to replace the pointer to a reader function with a pointer to a factory function, which returns an instance of a reader class, which derives from an abstract reader.

James Kanze
  • 150,581
  • 18
  • 184
  • 329