from here, if I put the overloaded operator in the namespace it should just work. But I found it actually not working, compiler always complain that it cannot find the << or >>.
In following example, if I turn on the USE_NAMESPACE, compiling fails. But the >> and << actually work outside the program_options. If I turn off the ENABLE_PO it works fine.
What happens here? how could I fix it?
#include <iostream>
#include <sstream>
#include <string>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#define ENABLE_PO 1
#define USE_NAMESPACE 0
enum class test_enum_t {bar, foo};
#if USE_NAMESPACE
namespace test_enum
{
#endif
template<typename istream_T>
istream_T& operator>>(istream_T& in, test_enum_t& value)
{
std::string in_str;
in >> in_str;
if (in_str == "bar")
value = test_enum_t::bar;
else if(in_str == "foo")
value = test_enum_t::foo;
else
in.setstate(std::ios_base::failbit);
return in;
}
template<typename ostream_T>
ostream_T &operator<<(ostream_T &out, const test_enum_t& value) {
if (value == test_enum_t::bar)
out << "bar";
else if (value == test_enum_t::foo)
out << "foo";
else
out << "unknown-value";
return out;
}
#if USE_NAMESPACE
}
using namespace test_enum;
#endif
#if ENABLE_PO
int simple_options(int argc, char *argv[])
{
test_enum_t test = test_enum_t::bar;
po::options_description config("Configuration");
config.add_options()
("help", "produce help message")
("in,i", po::value(&test)->default_value(test), "test enum class as input.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, config),vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << config << "\n";
return 1;
}
return 0;
}
#endif
int main(int argc, char *argv[])
{
#if ENABLE_PO
simple_options(argc, argv);
#endif
test_enum_t test;
std::cout << "input bar or foo" << std::endl;
std::cin >> test;
if (std::cin.fail())
{
std::cerr << "not a valid value";
exit(1);
}
std::cout << test << std::endl;
return 0;
}