This HowTo guides you through satisfying the requirements of sharg::parsable.
| Difficulty | Easy |
| Duration | 10 min |
| Prerequisite tutorials | |
| Recommended reading | |
Motivation
To use a custom type with sharg::parser::add_option or sharg::parser::add_positional_option, the type must satisfy sharg::parsable. This tutorial shows you what requirements must be met and supplies you with a copy and paste source for your code.
Concept sharg::parsable
As you can see in the API documentation of sharg::parsable, the type must model either both sharg::istreamable and sharg::ostreamable or sharg::named_enumeration.
If your type is an enum, refer to sharg::enumeration_names on how to make it compatible with the sharg::parser.
In all other cases, your type needs to model sharg::istreamable and sharg::ostreamable. As you can see in the respective documentation, the concept is simple. You merely need to supply the stream operators operator>>() and operator<<() for your type.
Make your own type compatible
- Note
- You must be able to modify the class itself for this solution to work.
The following example makes the class bar in namespace foo compatible with the sharg::parser:
namespace foo
{
class bar
{
public:
int a;
{
output << my_bar.a;
return output;
}
{
input >> my_bar.a;
return input;
}
};
}
int main(int argc, char const ** argv)
{
foo::bar my_bar{};
parser.add_option(my_bar,
try
{
parser.parse();
}
{
return -1;
}
return 0;
}
Meta-header for the Parser module .
Parser exception that is thrown whenever there is an error while parsing the command line arguments.
Definition: exceptions.hpp:43
The Sharg command line parser.
Definition: parser.hpp:156
@ off
Automatic update notifications should be disabled.
Option struct that is passed to the sharg::parser::add_option() function.
Definition: config.hpp:46
char short_id
The short identifier for the option (e.g. 'a', making the option callable via -a).
Definition: config.hpp:56
Make an external type compatible
If you cannot modify the class, you can do the following:
namespace external
{
class bar
{
public:
int a;
};
}
namespace std
{
ostream & operator<<(ostream & output, external::bar const & ext_bar)
{
output << ext_bar.a;
return output;
}
istream & operator>>(istream & input, external::bar & ext_bar)
{
input >> ext_bar.a;
return input;
}
}
int main(int argc, char const ** argv)
{
external::bar ext_bar{};
parser.add_option(ext_bar,
sharg::config{.
short_id =
'f', .long_id =
"ext-bar", .description =
"Supply an int."});
try
{
parser.parse();
}
{
return -1;
}
return 0;
}