2014-08-28 81 views
7

是否可以設置值的最小值和最大值(假設它是無符號短路,我需要介於0和10之間的值),因爲我可以通過設置默認值升壓程序選項設置選項的最小值和最大值

opt::value<unsigned short>()->default_value(5) 

我想立即使用程序選項的變量映射給出的參數,而不檢查它們中的每一個。

回答

7

不,你不能。 所有選項都被描述爲here。您可以手動檢查它們,或編寫函數,以手動檢查它們。

opt::value<unsigned short>()->default_value(5)->notifier(&check_function); 

其中檢查功能是一樣的東西

void check(unsigned short value) 
{ 
    if (value < 0 || value > 10) 
    { 
     // throw exception 
    } 
} 

或多個通用

template<typename T> 
void check_range(const T& value, const T& min, const T& max) 
{ 
    if (value < min || value > max) 
    { 
     // throw exception 
    } 
} 

opt::value<unsigned short>()->default_value(5)->notifier 
(boost::bind(&check_range<unsigned short>, _1, 0, 10)); 
+0

這是很好的答案,謝謝。 – 2014-08-28 11:59:49

7

在C++ 11這也可以使用lambda表達式來實現。

opt::value<unsigned short>() 
    ->default_value(5) 
    ->notifier(
     [](std::size_t value) 
     { 
     if (value < 0 || value > 10) { 
      // throw exception 
     } 
     }) 

這輕而易舉地保持接近呼叫點的驗證代碼本身並允許您自定義異常容易,像

throw opt::validation_error(
    opt::validation_error::invalid_option_value, 
    "option_name", 
    std::to_string(value)); 
7

我推薦一個lambda(如kaveish'sanswer)。但是你可以讓它返回一個函數來檢查適當的邊界,使所有的東西都更具可讀性。

auto in = [](int min, int max, char const * const opt_name){ 
    return [opt_name, min, max](unsigned short v){ 
    if(v < min || v > max){ 
     throw opt::validation_error 
     (opt::validation_error::invalid_option_value, 
     opt_name, std::to_string(v)); 
    } 
    }; 
}; 

opt::value<unsigned short>()->default_value(5) 
    ->notifier(in(0, 10, "my_opt")); 
+0

我很喜歡這個解決方案。一旦做了小小的調整 - 我使用'min','max'和'v'作爲模板參數來創建一個模板函數。 – alan 2017-10-30 20:21:57

相關問題