Skip to content

Commit 7efa8c6

Browse files
committed
✨ Add quick example
1 parent dbe98eb commit 7efa8c6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

examples/quick_example.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <iostream>
2+
#include <string_view>
3+
#include <unordered_map>
4+
#include <strtpl/string_template.hpp>
5+
6+
int main() {
7+
std::unordered_map<std::string_view, std::string_view> map{
8+
{"who", "Alice"},
9+
{"what", "bananas"},
10+
{"verb", "run"},
11+
};
12+
{ // '$' に続く単語を発見した場合、その単語を map の key として得られる値で置き換えます。
13+
std::cout << strtpl::substitute("$who likes $what.", map) << std::endl;
14+
// → Alice likes bananas.
15+
}
16+
{ // '$' と単語の後にアルファベットが続く場合は、単語を "{}" で囲みます。
17+
std::cout << strtpl::substitute("$who ${verb}s fast.", map) << std::endl;
18+
// → Alice runs fast.
19+
}
20+
// '$' に続く単語が map に含まれない場合、例外を送出します。
21+
try {
22+
std::cout << strtpl::substitute("$who likes $where.", map) << std::endl;
23+
} catch (const std::exception& e) {
24+
std::cout << e.what() << std::endl;
25+
// → strtpl::at: index out of range
26+
}
27+
// '$' に続く文字が無効な場合も、例外を送出します。エラーメッセージにはエラーが生じた文字の行番号と列番号を含みます。
28+
try {
29+
std::cout << strtpl::substitute("$who likes $.", map) << std::endl;
30+
} catch (const std::exception& e) {
31+
std::cout << e.what() << std::endl;
32+
// → Invalid placeholder in string: line 1, col 12
33+
}
34+
}

0 commit comments

Comments
 (0)