Question

I have a class which parses a document and calls a derived class to notify certain events found in the stream. Because the parser has to handle encodings and re write parts of the document into strings, I would like to avoid re-writing if the virtual method has not been over ridden. pseudocode:

class Parser
{
    virtual void Callback ( string )
    {
        // Do nothing
    }
private:
    void ParseFile()
    {
        // Parse the file in the files encoding
        // Checks and more checks
        // Found sth. So need to convert to a string a call the
        // callback, but if there is no callback what's the point
        // in wasting cycles?

        if ( Callback ) // In the world of C we could check for a func pointer
            Callback( /* with the string */ )
    }
}
class User : public Parser
{
    void Callback ( string )
    {
        // This string means sth. me
    }
}
class NonUser : public Parser
{
    // I don't care about Callback so I won't implement it
}

In C code, we would write a function and pass a pointer to that function to the implementation. Internally it would check if the pointer points to something and call it. How can the same be implemented with derived classes? ie. check if the virtual method actually exists in a derived class before wasting time/CPU cycles/memory constructing a string that may not even be required.

Compile time checking, providing it's portable, would be ideal, but I'm thinking this has something to do with v-tables so run time checking may also work.

After more research it has become apparent that v-tables are out, and that this is pretty much impossible. I'll change my question slightly to ask is the above possible using some type of, maybe template, trickery?

Was it helpful?

Solution

You could make the parameter a std::future, and go with the simple derived approach.

Or instead of string, pass in a proxy or a function that can provide it.

Or turn the table around, pass nothing and have a member function in Base that returns the string as it would be created.

Another approach is to have a virtual predicate function to the feature: in your base class it returns false, others return true, so you can call it before the real work doing. Alternatively it could return a pointer-to-function for the implementation, if it's likely to be doable in a static function. (And this can be passed as another param...)

It would be interesting to read you research concluding vtables out.

Templates only help you if you can tell the target at compile time. The problem as you stated it implies processing information that appears only at runtime. And that requires some pointers or other information actually passed around. But you might come up with a refined description of the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top