代码之家  ›  专栏  ›  技术社区  ›  Francois

boost::program\u options:当我自己的选项类型属于命名空间时,如何声明和验证它?

  •  3
  • Francois  · 技术社区  · 14 年前

    使用boost::program\u options,当我自己的选项类型在名称空间中声明时,我无法获得要编译的选项类型。但是,在命名空间之外,它可以编译并正常工作:

    #include <boost/program_options.hpp>
    using namespace boost;
    using namespace boost::program_options;
    
    struct my_type1 {
        my_type1(int nn) : n(nn) {}
        int n;
    };
    namespace nm  {
        struct my_type2 {
            my_type2(int nn) : n(nn) {}
            int n;
        };
    }
    
    void validate(boost::any& v,
                  const std::vector<std::string>& values,
                  my_type1*, int)  {
        const std::string& s = validators::get_single_string(values);
        v = any(my_type1(lexical_cast<int>(s)));
    }
    void validate(boost::any& v,
                  const std::vector<std::string>& values,
                  nm::my_type2*, int)  {
        const std::string& s = validators::get_single_string(values);
        v = any(nm::my_type2(lexical_cast<int>(s)));
    }
    
    int main()  {
        options_description desc("options");
        desc.add_options()
            ("m1", value<my_type1>()    , "")
            ("m2", value<nm::my_type2>(), "")
        ;
        return 0;
    }
    

    在main()中,选项“m1”的声明会编译,但“m2”不会。。。 少了什么?

    1 回复  |  直到 12 年前
        1
  •  5
  •   Lars    14 年前

    validate函数应该与结构位于同一命名空间中 my_type

      namespace nm  {
         void validate(boost::any& v,
                    const std::vector<std::string>& values,
                      my_type2*, int)  {
          const std::string& s = validators::get_single_string(values);
          v = any(my_type2(lexical_cast<int>(s)));
        }
      }
    

    它为我编写的。