Added mechanism to understand passed Option 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          * \attention If conversion from passed value to ArgumentType is
58          * impossible, it is ignored. It means that it is not understanded by
59          * Argument.
60          *
61          * @param argv command line value against which test will be made.
62          *
63          * @return If passed argv is succesfully converted to ArgumentType,
64          *  returns true and Argument is set as used one. If there was an error
65          *  during conversion, method returns false and can be used to check
66          *  against next value.
67          */
68         virtual bool understand(const std::string & argv) {
69             if (!used) {
70                 std::stringstream ss;
71
72                 ss << argv;
73                 ss >> argument;
74
75                 if (!ss.fail()) {
76                     used = true;
77                     return true;
78                 }
79             }
80
81             return false;
82         }
83     };
84 }
85
86 #endif /* __COMMAND_ARGUMENT_H */