怀疑使用boost :: program_options

时间:2015-09-04 10:10:25

标签: c++ boost boost-program-options

我在我的一个应用程序中使用boost::program_options。有了它,我几乎填写了所有类参数。

由于我需要将“选项”传递给不同的类,我在全局范围内声明variable_map并在类头文件中将其作为extern传递。

像这样( main.cpp ):

boost::program_options::variables_map vm;

int main(int argc, char* argv[]) {

    using namespace boost::program_options;
    try {
        options_description desc("Allowed options");
        desc.add_options()
        ("help,h", "produce help message")
        ("control-port,c", value<uint16_t>()->implicit_value(6016),
          "The remote TCP port used for listen to probe control connections")
        ("data-port", value<uint16_t>()->implicit_value(6026),
          "The remote TCP port used for listen to probe data connections")
        ("db-host", value<std::string>(),
          "The host name or address of MySQL database")
        ("db-port", value<uint16_t>(), "The port of MySQL database"
        ("db-user", value<std::string>(),
          "The username used to connect to MySQL database")
        ("db-pass", value<std::string>(),
          "The password used to connect to MySQL database")
        ("db-schema", value<std::string>(), "The database scheme used");

...

(的 DbConnector.hpp

extern boost::program_options::variables_map vm;

(的 DbConnector.cpp

 ...
DbConnector::DbConnector(const std::string& ownerName_) :
        ownerName(ownerName_) {
    dbHost = vm["db-host"].as<std::string>();
    dbPort = vm["db-port"].as<uint16_t>();
    dbUser = vm["db-user"].as<std::string>();
    dbPass = vm["db-pass"].as<std::string>();
    dbSchema = vm["db-schema"].as<std::string>();
  ...

等等,对于其他课程..

我想知道是否有更好的方法来实现这一点,可能会避免使用extern关键字。

0 个答案:

没有答案