2017-02-08 8 views
0

boost::program_options::variables_map을 편집하여 첫 번째 위치 옵션에 따라 암시 된 옵션을 추가하려고합니다. 그러나 boost::variables_map에서 사용할 때 po::store을 사용하면 두 번째로 작동하지 않습니다. 여기 `boost :: program_options`는`variables_map`에서`store`를 두 번 사용할 수 없습니다

이 실패 할 최소한의 예입니다 저장되지되었다 즉

dummy-int 3 
verbose 

dummy-int 3 
verbose 

, 옵션 dummy :

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

namespace po = boost::program_options; 

std::ostream &operator<<(std::ostream &s, po::variables_map const &vm) 
{ 
    for (const auto& it : vm) 
    { 
     s << it.first.c_str() << " "; 
     auto& value = it.second.value(); 
     if (auto v = boost::any_cast<char>(&value)) 
      s << *v; 
     else if (auto v = boost::any_cast<short>(&value)) 
      s << *v; 
     else if (auto v = boost::any_cast<int>(&value)) 
      s << *v; 
     else if (auto v = boost::any_cast<long>(&value)) 
      s << *v; 
     else if (auto v = boost::any_cast<std::string>(&value)) 
      s << *v; 
     else if (auto v = boost::any_cast<std::vector<std::string>>(&value)) 
     { 
      s << "["; 
      for(const auto &w : *v) 
       s << " " << w; 
      s << " ]"; 
     } 
     else 
      s << "<?>"; 
     s << '\n'; 
    } 
    return s; 
} 

int main(int argc, char **argv) 
{ 
    po::options_description desc("Options"); 
    desc.add_options() 
     ("help","show this help message") 
     ("verbose","print extra messages") 
     ("dummy","pointless") 
     ("dummy-int", po::value<int>(), "pointless") 
     ("dummy-str", po::value<std::string>(), "pointless") 
    ; 

    po::variables_map vm; 
    po::store(po::parse_command_line(argc, argv, desc), vm); 
    po::notify(vm); 

    bool verbose = vm.count("verbose"); 

    if(verbose) 
     std::cout << vm << std::endl; 

    if(vm.count("help")) 
    { 
     std::cout << desc << std::endl; 
     return 0; 
    } 

    const char* newOption = "--dummy"; 
    po::store(po::parse_command_line(1, &newOption, desc), vm); 
    po::notify(vm); 

    if(verbose) 
     std::cout << vm << std::endl; 

    return 0; 
} 

건물을하고 프로그램을 실행, 나는 터미널에 볼 수 있습니다 vm에! 왜 찾을 수 있도록 도와 주실 수 있습니까? 어떤 도움을 주셔서 감사합니다!

+0

고마워요! 질문에 답을 표시 할 수 있도록 대답에서 말 했어야합니다 ... –

+0

완료 :) 지금은 중복되어 있기 때문에 주석을 삭제하고 거기에 오타가 있음을 발견했습니다. –

답변

2

첫 번째 인수는 특별한 의미가 있다는 것을 잊었습니다 - 호출 된 프로그램의 이름입니다.

documentation에 따르면

argv[0]이 경우 프로그램 자체 (또는 빈 문자열 ""호출하는 데 사용되는 이름을 나타냅니다 null로 끝나는 멀티 바이트 문자열의 첫 문자에 대한 포인터입니다 실행 환경에서 지원되지 않음). 스 니펫

const char* newOption = "--dummy"; 
po::store(po::parse_command_line(1, &newOption, desc), vm); 

에서

당신은 당신이 인수를 공급하지 않는 것을 의미 argv로 하나 개의 요소 배열을 전달하고 도서관 구문 분석 할 아무것도 없다. 따라서 variable_map 인스턴스에는 아무 것도 추가되지 않습니다.