C++字符串模板库

9 c++ string

我想要简单的基于C++字符串的模板库来在运行时替换字符串.

例如,我会用

string template = "My name is {{name}}";
Run Code Online (Sandbox Code Playgroud)

在运行时,我希望根据实际名称更改名称.

我找到了一个例子,www.stringtemplate.org但是当我谈到antlr等时我有点害怕.

mat*_*ias 14

更新:项目已移至Github并重命名为CTemplate:https://github.com/OlafvdSpek/ctemplate

从新项目页面:

最初被称为Google模板,因为它起源于用于Google搜索结果页面的模板系统.现在它有一个更符合社区所有性的通用名称.


您是否尝试过Google的CTemplate库?它似乎正是您所寻找的:http://code.google.com/p/google-ctemplate/

您的示例将实现如下:

在example.tpl中:

我的名字是{{name}}

在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;
}
Run Code Online (Sandbox Code Playgroud)

然后:

$ gcc example.cc -lctemplate -pthread

$ ./a.out
Run Code Online (Sandbox Code Playgroud)

我叫约翰史密斯

请注意,如果您不想在单独的文件中编写模板,还可以将模板编写为常量字符串.


str*_*ger 6

你能用sprintf吗?

还有boost::format,如果你想包括提升.

  • 我很惊讶你甚至没有因为提到'sprintf`而受到死亡威胁.但这就是我使用的,所以+1 :) (3认同)
  • \*死亡威胁\*@John:那里,现在这个答案已经完成了. (2认同)