2015-10-28 52 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; 
}