Added mechanism to understand passed Option without 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      *  ./myprog /path/to/file
20      *  ./myprog "some argument"
21      */
22     template<typename ArgumentType>
23     class Argument : public Parameter, public Callable<ArgumentType> {
24     protected:
25         /** Variable indicating if current Argument was already used or not */
26         bool used = false;
27
28         ArgumentType argument;
29     public:
30         typedef class Argument Type;
31
32         /**
33          * Default constructor.
34          *
35          * @param description Description of current Argument
36          * @param function Function used to handle current Argument.
37          */
38         Argument(const std::string & description, void (*function)(ArgumentType))
39             : Parameter(description), Callable<ArgumentType>(function) {
40         }
41
42         /**
43          *
44          */
45         virtual ~Argument() { }
46
47         /**
48          *
49          */
50         virtual void handle() {
51             this->call(argument);
52         }
53
54         /**
55          * Method used for checking if Argument understands user value.
56          * If so current Argument is flagged as used and no more checks against
57          * it will be done in future.
58          *
59          * \attention If conversion from passed value to ArgumentType is
60          * impossible, it is ignored. It means that it is not understanded by
61          * Argument.
62          *
63          * @param argv command line value against which test will be made.
64          *
65          * @return If passed argv is succesfully converted to ArgumentType,
66          *  returns true and Argument is set as used one. If there was an error
67          *  during conversion, method returns false and can be used to check
68          *  against next value.
69          */
70         virtual bool understand(const std::string & argv) {
71             if (!used) {
72                 std::stringstream ss;
73
74                 ss << argv;
75                 ss >> argument;
76
77                 if (!ss.fail()) {
78                     used = true;
79                     return true;
80                 }
81             }
82
83             return false;
84         }
85     };
86 }
87
88 #endif /* __COMMAND_ARGUMENT_H */