/
Command.h
76 lines (62 loc) · 1.79 KB
/
Command.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#ifndef _COMMAND_H_
#define _COMMAND_H_
#include "itextstream.h"
#include "Executable.h"
namespace cmd {
class Command :
public Executable
{
// The actual function to call
Function _function;
// The number and types of arguments to use
Signature _signature;
public:
Command(const Function& function, const Signature& signature) :
_function(function),
_signature(signature)
{}
Signature getSignature() {
return _signature;
}
virtual void execute(const ArgumentList& args) {
// Check arguments
if (_signature.size() < args.size()) {
// Too many arguments, that's for sure
rError() << "Cannot execute command: Too many arguments. "
<< "(max. " << _signature.size() << " arguments required)" << std::endl;
return;
}
// Check matching arguments
ArgumentList::const_iterator arg = args.begin();
for (Signature::const_iterator cur = _signature.begin(); cur != _signature.end(); ++cur) {
std::size_t curFlags = *cur;
bool curIsOptional = ((curFlags & ARGTYPE_OPTIONAL) != 0);
// If arguments have run out, all remaining parts of the signature must be optional
if (arg == args.end()) {
// Non-optional arguments will cause an error
if (!curIsOptional) {
rError() << "Cannot execute command: Missing arguments. " << std::endl;
return;
}
}
else {
// We have incoming arguments to match our signature
if ((curFlags & arg->getType()) == 0) {
// Type mismatch
rError() << "Cannot execute command: Type mismatch at argument: "
<< arg->getString() << std::endl;
return;
}
}
// Increase argument iterator if possible
if (arg != args.end()) {
++arg;
}
}
// Checks passed, call the command
_function(args);
}
};
typedef std::shared_ptr<Command> CommandPtr;
} // namespace cmd
#endif /* _COMMAND_H_ */