Evgenii Legotckoi
Dec. 5, 2018, 4:47 a.m.

Boost - Use enum in parameters boost::program_options

A small addition to the article on the use of boost::program_options .

In this appendix I will describe how to use enum enums. Because immediately they do not work. By default, boost::program_options work only with basic types and some types from the standard library, for example std::string .


Suppose we have a class that contains an enum .

  1. class Logger
  2. {
  3. public:
  4. explicit Logger();
  5.  
  6. enum VerboseLevel
  7. {
  8. E_DEBUG = 0
  9. E_INFO,
  10. E_WARNING,
  11. E_CRITICAL,
  12. };
  13. };

It is logical that we would like to use this enumeration in the command line menu to set the level of detail of the output in the console or in a file for example.

That is, we want to configure our boost::program_options like this.

  1. m_desc.add_options()
  2. (MENU_ITEM_HELP.c_str(), "produce help message")
  3. ("level",
  4. po::value<Logger::VerboseLevel>(&m_verboseLevel)->default_value(Logger::E_WARNING),
  5. "set verbose level of logging, default level is Info\nLevels: \n0) Debug \n1) Info \n2) Warning \n3) Critical")
  6. ;
  7. po::store(po::parse_command_line(argc, argv, m_desc), m_vm);
  8. po::notify(m_vm);

But when building we get an error

  1. Error C2338 Target type is neither std::istream`able nor std::wistream`able

In this case, we need to do an overload on operator>> in order to be able to set the values we need.

The simplest option might look like this.

  1. std::istream& operator>>(std::istream& in, Logger::VerboseLevel& verboseLevel)
  2. {
  3. std::string token;
  4. in >> token;
  5. if (token == "0")
  6. verboseLevel = Logger::VerboseLevel::E_DEBUG;
  7. else if (token == "1")
  8. verboseLevel = Logger::VerboseLevel::E_INFO;
  9. else if (token == "2")
  10. verboseLevel = Logger::VerboseLevel::E_WARNING;
  11. else if (token == "3")
  12. verboseLevel = Logger::VerboseLevel::E_CRITICAL;
  13. else
  14. in.setstate(std::ios_base::failbit);
  15. return in;
  16. }

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html