C ++字符串模板库 [英] C++ string template library
问题描述
我想要简单的基于C ++字符串的模板库在运行时替换字符串。
I want simple C++ string based template library to replace strings at runtime.
例如,我将使用
string template = "My name is {{name}}";
在运行时,我想根据实际情况更改名称。
At runtime, I want the name to be changed based on actual one.
我发现了一个例子,www.stringtemplate.org,但是我在讨论antlr等时很害怕。
I found one example, www.stringtemplate.org but I little scared when its talks about antlr etc.
推荐答案
您是否尝试过google的CTemplate库?这似乎正是你要找的:
http://code.google.com/p/ google-ctemplate /
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:
:
我的名字是{{name}}
My name is {{name}}
在example.cc中:
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;
}
然后:
$ gcc example.cc -lctemplate -pthread
$ ./a.out
我的名字是John Smith
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.
这篇关于C ++字符串模板库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!