CTemplate Emitter for Stream Output

Google’s CTemplate has very customizable output features, yet it does not come with an emitter (the type of class that actually outputs the template with all the variables filled in) for standard streams.  Hence there is no default way to output to std::cout.

Or I was unable to find one.

Therefore, here is a very simple emitter for stream output.

class StreamEmitter: public ctemplate::ExpandEmitter
{
public:
    StreamEmitter( std::ostream &out ) : sout( out )
    {
    }

    virtual void Emit( char c )
    {
        sout << c;
    }

    virtual void Emit( const std::string &s )
    {
        sout << s;
    }

    virtual void Emit( const char *s )
    {
        sout << s;
    }

    virtual void Emit( const char *s, size_t len )
    {
        sout.write( s, len );
    }

private:
    std::ostream &sout;
};

Then it can be used like this.

// Assume pageDict has been initialized and the variables filled in...

    StreamEmitter coutEmitter( std::cout );

    ctemplate::ExpandTemplate( "template_file", ctemplate::DO_NOT_STRIP, &pageDict, &coutEmitter );

Am I really the only one who wants to emit templates to streams?


Licenese: Three clause BSD (same as CTemplate itself).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: