Skip to content

Instantly share code, notes, and snippets.

@letmaik
Forked from gesquive/print-program-options.cc
Last active January 19, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letmaik/6569d1ea6cbbc1088daabe04dcf614f7 to your computer and use it in GitHub Desktop.
Save letmaik/6569d1ea6cbbc1088daabe04dcf614f7 to your computer and use it in GitHub Desktop.
Methods to print out boost::program_options objects (C++11)
#include <string.h>
#include <iostream>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include "boost/any.hpp"
namespace po = boost::program_options;
inline void PrintUsage(const boost::program_options::options_description desc) {
std::cout << "Usage: " << app_name << " [options]" << std::endl;
std::cout << " App description" << std::endl;
std::cout << desc << std::endl;
std::cout << std::endl << "v" << VERSION << std::endl;
}
inline void PrintVariableMap(const boost::program_options::variables_map vm) {
for (auto it : vm) {
std::cout << "> " << it.first;
if (((boost::any)it.second.value()).empty()) {
std::cout << "(empty)";
}
if (vm[it.first].defaulted() || it.second.defaulted()) {
std::cout << "(default)";
}
std::cout << "=";
bool is_char;
try {
boost::any_cast<const char *>(it.second.value());
is_char = true;
} catch (const boost::bad_any_cast &) {
is_char = false;
}
bool is_str;
try {
boost::any_cast<std::string>(it.second.value());
is_str = true;
} catch (const boost::bad_any_cast &) {
is_str = false;
}
if (((boost::any)it.second.value()).type() == typeid(int)) {
std::cout << vm[it.first].as<int>() << std::endl;
} else if (((boost::any)it.second.value()).type() == typeid(long)) {
std::cout << vm[it.first].as<long>() << std::endl;
} else if (((boost::any)it.second.value()).type() == typeid(bool)) {
std::cout << vm[it.first].as<bool>() << std::endl;
} else if (((boost::any)it.second.value()).type() == typeid(double)) {
std::cout << vm[it.first].as<double>() << std::endl;
} else if (((boost::any)it.second.value()).type() == typeid(float)) {
std::cout << vm[it.first].as<float>() << std::endl;
} else if (is_char) {
std::cout << vm[it.first].as<const char * >() << std::endl;
} else if (is_str) {
std::string temp = vm[it.first].as<std::string>();
if (temp.size()) {
std::cout << temp << std::endl;
} else {
std::cout << "true" << std::endl;
}
} else { // Assumes that the only remainder is vector<string>
try {
std::vector<std::string> vect = vm[it.first].as<std::vector<std::string> >();
auto i = 0;
for (std::vector<std::string>::iterator oit=vect.begin();
oit != vect.end(); oit++, ++i) {
std::cout << "\r> " << it.first << "[" << i << "]=" << (*oit) << std::endl;
}
} catch (const boost::bad_any_cast &) {
std::cout << "UnknownType(" << ((boost::any)it.second.value()).type().name() << ")" << std::endl;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment