Possibility to handle class method & example
[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, std::function<void(ParameterType)> function)
36             : Parameter(description), Callable<ParameterType>(function) {
37         }
38
39         /**
40          *
41          */
42         virtual ~Argument() { }
43
44         /**
45          * \inheritdoc
46          */
47         virtual void handle() {
48             this->call(value);
49             this->used = true;
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 ParameterType 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 ParameterType,
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             std::stringstream ss;
70
71             ss << std::fixed << argv;
72             ss >> value;
73
74             if (!ss.fail()) {
75                 return true;
76             }
77
78             return false;
79         }
80
81         /**
82          * \inheritdoc
83          */
84         virtual unsigned int valuePosition(const std::string & ) {
85             return 0;
86         }
87     };
88 }
89
90 #endif /* __COMMAND_ARGUMENT_H */