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