In the example (regex.cpp), the author of the library created a custom struct (magic_number) and a validate function for this struct to show how custom struct can be integrated into program options. I followed his example to create a validate function for a custom class (MyClass). Compiler complains that a lexical_cast is not available for MyClass. I then implemented std::istream& operator>>(std::istream& in, MyClass& d)
, removed void validate(.., MyClass*, ..)
, the code compiles. Can anyone explain why the example doesn't require operator>>
, while mine doesn't require validate
?
EDIT:
#include <MyLib/MyClass.h>
std::istream& operator>>(std::istream& in, MyClass& obj) {
// some code to populate obj
return in;
}
po::variables_map parseCommandLine(int argc, char* argv[]) {
po::options_description options("Options");
options.add_options()
("help", "produce help message")
("obj", po::value<MyClass>(), "")
;
po::variables_map vm;
store(po::command_line_parser(argc, argv)
.options(options).run(), vm);
notify(vm);
return vm;
}
int main(int argc, char* argv[]) {
try {
po::variables_map vm = parseCommandLine(argc, argv);
MyClass obj = vm["my"].as<MyClass>();
cout << obj << endl;
} catch(std::exception& e) {
cout << e.what() << "\n";
return 1;
}
return 0;
}
- the code compiles without validate.
I also tried making minimum change to regex.cpp:
- remove magic_number
- add
#include <MyLib/MyClass.h>
- replace all occurance of magic_number by MyClass.
- comment out all code in validate.
- This does not compile.
EDIT: add validate
. None of them solved the compiler error.
void validate(boost::any& v,
const std::vector<std::string>& values,
std::vector<MyClass>*, int)
{
}
void validate(boost::any& v,
const std::vector<std::string>& values,
MyClass*, long)
{
}
void validate(boost::any& v,
const std::vector<std::string>& values,
MyClass*, int)
{
}
EDIT: It may relate to namespaces.
After I surrounded the validate function by namespace boost { namespace program_options { }}
, the code compiled without overloading op>>. It also works if validate is put into the same namespace as MyClass. Can anyone explain this?