2015-10-28 50 views
1

我写一个使用Boost的程序选项库的程序,我不能够使用boost验证文件扩展名::程序选项:如何使用boost :: progam_option验证文件扩展名和boost :: command_line_Parser

po::options_description desc("Allowed options"); 
    desc.add_options() 
     ("help", "produce help message") 
     ("diff,d", po::value<std::string>(),"Specify the .xyz file, name of the .xyz to create")**.xyz file I want to validate,while givin input as comman line ** 
    ; 

    po::variables_map vm; 
    po::store(po::parse_command_line(ac, av, desc), vm); 
    po::notify(vm); 
+0

什么文件扩展名。 – sehe

+0

(“diff,d”,po :: value (),“指定.xyz文件,要创建的.xyz的名称”)在这里,我想验证.xya文件扩展名,@sehe –

+1

多德。为什么这不是你的问题?点击[编辑](http://stackoverflow.com/posts/33383822/edit)也许? – sehe

回答

1

好吧,你需要实现validate

您可以使用一个标签类型,这样可以关联您的validate通过Argument Dependent Lookup

Live On Coliru

#include <boost/program_options.hpp> 
#include <boost/algorithm/string.hpp> 
#include <vector> 
#include <iostream> 

namespace tag { 
    struct xyz_file {}; 

    bool validate(boost::any& v, std::vector<std::string> const& ss, xyz_file*, int) { 
     if (ss.size() == 1 && boost::algorithm::iends_with(ss.front(), ".xyz")) 
     { 
      v = ss.front(); 
      return true; 
     } 
     return false; 
    } 
} 

namespace po = boost::program_options; 

int main(int ac, char** av) { 
    po::options_description desc("Allowed options"); 
    desc.add_options() 
     ("diff,d", po::value<tag::xyz_file>(), "xyz files only") 
     ; 

    po::variables_map vm; 

    po::store(po::parse_command_line(ac, av, desc), vm); 
    po::notify(vm); 

    if (!vm["diff"].empty()) 
     std::cout << "Parsed: " << vm["diff"].as<std::string>() << "\n"; 
    else 
     std::cout << desc; 
}