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