Fix github's markdown display of README file
[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             this->used = true;
49         }
50
51         /**
52          * Method used for checking if Argument understands user value.
53          * If so current Argument is flagged as used and no more checks against
54          * it will be done in future.
55          *
56          * \attention If conversion from passed value to ParameterType is
57          * impossible, it is ignored. It means that it is not understanded by
58          * Argument.
59          *
60          * @param argv command line value against which test will be made.
61          *
62          * @return If passed argv is succesfully converted to ParameterType,
63          *  returns true and Argument is set as used one. If there was an error
64          *  during conversion, method returns false and can be used to check
65          *  against next value.
66          */
67         virtual bool understand(const std::string & argv) {
68             std::stringstream ss;
69
70             ss << std::fixed << argv;
71             ss >> value;
72
73             if (!ss.fail()) {
74                 return true;
75             }
76
77             return false;
78         }
79
80         /**
81          * \inheritdoc
82          */
83         virtual unsigned int valuePosition(const std::string & ) {
84             return 0;
85         }
86     };
87 }
88
89 #endif /* __COMMAND_ARGUMENT_H */