Skip to content

Commit e147009

Browse files
committed
updated example. Demonstrate pass by reference
1 parent eb124ba commit e147009

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

examples/t08_additional_node_args.cpp

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@
22

33
using namespace BT;
44

5+
// To demonstrate how to pass arguments by reference, we
6+
// use a simple non-copyable object
7+
class NoCopyObj {
8+
public:
9+
NoCopyObj(int val): _value(val) {}
10+
11+
NoCopyObj(const NoCopyObj& ) = delete;
12+
NoCopyObj& operator =(const NoCopyObj& ) = delete;
13+
int value() { return _value; }
14+
private:
15+
int _value = 0;
16+
};
17+
518
/*
619
* Sometimes, it is convenient to pass additional (static) arguments to a Node.
720
* If these parameters are known at compilation time or at deployment-time
@@ -17,13 +30,14 @@ class Action_A : public SyncActionNode
1730
public:
1831
// additional arguments passed to the constructor
1932
Action_A(const std::string& name, const NodeConfig& config, int arg_int,
20-
std::string arg_str) :
21-
SyncActionNode(name, config), _arg1(arg_int), _arg2(arg_str)
33+
std::string arg_str, NoCopyObj& nc) :
34+
SyncActionNode(name, config), _arg1(arg_int), _arg2(arg_str), _nc(nc)
2235
{}
2336

2437
NodeStatus tick() override
2538
{
26-
std::cout << name() << ": " << _arg1 << " / " << _arg2 << std::endl;
39+
std::cout << name() << ": " << _arg1 << " / "
40+
<< _arg2 << " / " << _nc.value() << std::endl;
2741
return NodeStatus::SUCCESS;
2842
}
2943
static PortsList providedPorts()
@@ -34,6 +48,7 @@ class Action_A : public SyncActionNode
3448
private:
3549
int _arg1;
3650
std::string _arg2;
51+
NoCopyObj& _nc;
3752
};
3853

3954
// Action_B implements an init(...) method that must be called once at the beginning.
@@ -83,8 +98,13 @@ int main()
8398
{
8499
BehaviorTreeFactory factory;
85100

101+
NoCopyObj non_copyable(88);
102+
86103
// Passing the extra parameters to the constructor of Action_A
87-
factory.registerNodeType<Action_A>("Action_A", 42, "hello world");
104+
// note that if you want to pass an object by ref, instead of value
105+
// (copy), you must use std::ref wrapper.
106+
factory.registerNodeType<Action_A>("Action_A", 42, "hello world",
107+
std::ref(non_copyable));
88108

89109
// Action_B will require initialization
90110
factory.registerNodeType<Action_B>("Action_B");
@@ -103,7 +123,7 @@ int main()
103123
tree.tickWhileRunning();
104124

105125
/* Expected output:
106-
Action_A: 42 / hello world
126+
Action_A: 42 / hello world / 88
107127
Action_B: 69 / interesting_value
108128
*/
109129
return 0;

0 commit comments

Comments
 (0)