Skip to content

Commit a6cf4c5

Browse files
committed
opt(util): 为Variables添加get()模板函数,方便使用
1 parent 196a173 commit a6cf4c5

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

modules/flow/to_graphviz_test.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,10 @@ TEST(ToGraphviz, ActionJson) {
4141

4242
auto seq_action = new SequenceAction(*loop);
4343
seq_action->set_label("This is test");
44+
seq_action->vars().define("seq.value", 12);
4445
auto if_else_action = new IfElseAction(*loop);
46+
if_else_action->vars().define("if_else.name", "hello");
47+
if_else_action->vars().define("if_else.value", 100);
4548
if_else_action->setChildAs(new SuccAction(*loop), "if");
4649
if_else_action->setChildAs(new FunctionAction(*loop, []{return true;}), "succ");
4750
if_else_action->setChildAs(new FunctionAction(*loop, []{return true;}), "fail");

modules/util/variables.h

+10
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#include <map>
2424
#include <tbox/base/defines.h>
2525
#include <tbox/base/json_fwd.h>
26+
#include <tbox/util/json.h>
2627

2728
namespace tbox {
2829
namespace util {
@@ -78,6 +79,15 @@ class Variables {
7879
*/
7980
bool get(const std::string &name, Json &js_out_value, bool local_only = false) const;
8081

82+
//! 获取变量的模板
83+
template <typename T>
84+
bool get(const std::string &name, T &out_value, bool local_only = false) const {
85+
Json js;
86+
if (get(name, js, local_only))
87+
return json::Get(js, out_value);
88+
return false;
89+
}
90+
8191
/**
8292
* 更新变量
8393
*

modules/util/variables_test.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,31 @@ TEST(Variables, Base) {
4242
EXPECT_FALSE(vars.has("a"));
4343
}
4444

45+
TEST(Variables, GetTemplate) {
46+
Variables vars;
47+
48+
EXPECT_TRUE(vars.define("b", true));
49+
EXPECT_TRUE(vars.define("i", 12));
50+
EXPECT_TRUE(vars.define("s", "hello"));
51+
EXPECT_TRUE(vars.define("d", 12.345));
52+
53+
bool b = false;
54+
int i = 0;
55+
std::string s;
56+
double d = 0;
57+
58+
EXPECT_TRUE(vars.get("b", b));
59+
EXPECT_TRUE(vars.get("i", i));
60+
EXPECT_TRUE(vars.get("s", s));
61+
EXPECT_TRUE(vars.get("d", d));
62+
EXPECT_FALSE(vars.get("s", d));
63+
64+
EXPECT_TRUE(b);
65+
EXPECT_EQ(i, 12);
66+
EXPECT_EQ(s, "hello");
67+
EXPECT_DOUBLE_EQ(d, 12.345);
68+
}
69+
4570
TEST(Variables, RepeatDefine) {
4671
Variables vars;
4772
EXPECT_TRUE(vars.define("a", 12));

version.mk

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@
2121
# TBOX版本号
2222
TBOX_VERSION_MAJOR := 1
2323
TBOX_VERSION_MINOR := 11
24-
TBOX_VERSION_REVISION := 7
24+
TBOX_VERSION_REVISION := 8

0 commit comments

Comments
 (0)