Added mechanism to understand passed Argument value.
[command.git] / include / argument.h
1 #ifndef __COMMAND_ARGUMENT_H
2 #define __COMMAND_ARGUMENT_H
3
4 #include <string>
5 #include <sstream>
6 #include <iostream>
7
8 #include "parameter.h"
9 #include "callable.h"
10
11 namespace command {
12     /**
13      * Class responsible for handling commandline arguments.
14      * Arguments are required, non-named parameters of program.
15      * Accepts
16      *
17      * Example:
18      *  ./myprog ARGUMENT
19      */
20     template<typename ArgumentType>
21     class Argument : public Parameter, public Callable<ArgumentType> {
22     protected:
23         /** Variable indicating if current Argument was already used or not */
24         bool used = false;
25
26         ArgumentType argument;
27     public:
28         typedef class Argument Type;
29
30         /**
31          * Default constructor.
32          *
33          * @param description Description of current Argument
34          * @param function Function used to handle current Argument.
35          */
36         Argument(const std::string & description, void (*function)(ArgumentType))
37             : Parameter(description), Callable<ArgumentType>(function) {
38         }
39
40         /**
41          *
42          */
43         virtual ~Argument() { }
44
45         /**
46          *
47          */
48         virtual void handle() {
49             this->call(argument);
50         }
51
52         /**
53          * Method used for checking if Argument understands user value.
54          * If so current Argument is flagged as used, and no more checks against
55          * it will be done in future.
56          *
57          * If conversion from passed value to ArgumentType is impossible, it is
58          * ignored.
59          *
60          * @param argv command line value against which test will be made.
61          *
62          * @return If passed argv is succesfully converted to ArgumentType,
63          *  returns true, and Argument is set as used one. If there was an error
64          *  during conversion, method returns false and can be used to check
65          *  against next value.
66          */
67         virtual bool understand(const std::string & argv) {
68             if (!used) {
69                 std::stringstream ss;
70
71                 ss << argv;
72                 ss >> argument;
73
74                 if (!ss.fail()) {
75                     used = true;
76                     return true;
77                 }
78             }
79
80             return false;
81         }
82     };
83 }
84
85 #endif /* __COMMAND_ARGUMENT_H */