خيارات قصيرة فقط في Boost :: Program_options
-
26-09-2019 - |
سؤال
كيف يمكن للمرء أن يحدد خيارات قصيرة دون نظرائهم الطويلة في Boost؟
(",w", po::value<int>(), "Perfrom write with N frames")
يولد هذا
-w [ -- ] arg : Perfrom write with N frames
أي طريقة لتحديد الخيارات القصيرة فقط؟
المحلول
إذا كنت تستخدم محلل سطر الأوامر ، فهناك طريقة لتعيين أنماط مختلفة. لذلك سيكون الحل هو استخدام خيارات طويلة فقط وتمكين نمط ALLE_LONG_DISGUISE الذي يسمح بتحديد خيارات طويلة مع اندفاعة واحدة (أي "-long_option"). هنا مثال:
#include <iostream>
#include <boost/program_options.hpp>
namespace options = boost::program_options;
using namespace std;
int
main (int argc, char *argv[])
{
options::options_description desc (string (argv[0]).append(" options"));
desc.add_options()
("h", "Display this message")
;
options::variables_map args;
options::store (options::command_line_parser (argc, argv).options (desc)
.style (options::command_line_style::default_style |
options::command_line_style::allow_long_disguise)
.run (), args);
options::notify (args);
if (args.count ("h"))
{
cout << desc << endl;
return 0;
}
}
ستكون هناك مشكلة صغيرة في إخراج الوصف:
$ ./test --h
./test options:
--h Display this message
ومن الصعب إصلاح ذلك لأن هذا هو ما يتم استخدامه لتشكيل هذا الإخراج:
std::string
option_description::format_name() const
{
if (!m_short_name.empty())
return string(m_short_name).append(" [ --").
append(m_long_name).append(" ]");
else
return string("--").append(m_long_name);
}
الإصلاح الوحيد لهذا يتبادر إلى الذهن هو استبدال "-" مع "-" في السلسلة الناتجة. علي سبيل المثال:
#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/replace.hpp>
namespace options = boost::program_options;
using namespace std;
int
main (int argc, char *argv[])
{
options::options_description desc (string (argv[0]).append(" options"));
desc.add_options()
("h", "Display this message")
;
options::variables_map args;
options::store (options::command_line_parser (argc, argv).options (desc)
.style (options::command_line_style::default_style |
options::command_line_style::allow_long_disguise)
.run (), args);
options::notify (args);
if (args.count ("h"))
{
std::stringstream stream;
stream << desc;
string helpMsg = stream.str ();
boost::algorithm::replace_all (helpMsg, "--", "-");
cout << helpMsg << endl;
return 0;
}
}
أفضل شيء يمكنك القيام به هو إصلاح الرمز الذي يطبع فيه الوصف الفارغ للخيار الطويل وإرسال تصحيح إلى مؤلف المكتبة.
لا تنتمي إلى StackOverflow