C++ string template library

Can you use sprintf?

There's also boost::format if you want to include boost.


If you have a function that replaces all occurrences of a string with another string:

std::string replace_all(std::string str, const std::string &remove, const std::string &insert) 
{
    std::string::size_type pos = 0;
    while ((pos = str.find(remove, pos)) != std::string::npos)
    {
        str.replace(pos, remove.size(), insert);
        pos++;
    }

    return str;
}

Then you can do this:

std::string pattern = "My name is {{first_name}} {{last_name}} and I live in {{location}}";

std::string str = replace_all(replace_all(replace_all(pattern, 
                       "{{first_name}}", "Homer"), 
                       "{{last_name}}", "Simpson"), 
                       "{{location}}", "Springfield");

Update: The project has moved to Github and renamed into CTemplate: https://github.com/OlafvdSpek/ctemplate

From the new project page:

was originally called Google Templates, due to its origin as the template system used for Google search result pages. Now it has a more general name matching its community-owned nature.


Have you tried Google's CTemplate library ? It seems to be exactly what you are looking for: http://code.google.com/p/google-ctemplate/

Your example would be implemented like this:

In example.tpl:

My name is {{name}}

In example.cc:

#include <stdlib.h>
#include <string>
#include <iostream>
#include <google/template.h>

int main(int argc, char** argv)
{
  google::TemplateDictionary dict("example");
  dict.SetValue("name", "John Smith");
  google::Template* tpl = google::Template::GetTemplate("example.tpl",
                                                        google::DO_NOT_STRIP);
  std::string output;
  tpl->Expand(&output, &dict);
  std::cout << output;
  return 0;
}

Then:

$ gcc example.cc -lctemplate -pthread

$ ./a.out

My name is John Smith

Note that there is also a way to write templates as const strings if you don't want to bother writting your templates in separate files.

Tags:

C++

String