我有呈三角這樣的功能:一些方法提前歸還時不需要完全計算
void fillset(std::set<int>& myset)
{
while(...) {
object[i]->fillset(myset);
}
if(...)
otherfillset(myset)
}
現在我發現,經常使用此函數是這樣的:
bool isAllowed() {
std::set<int> myset;
fillset(myset);
return !myset.empty();
}
現在,在這種情況下調用整個fillset()方法是沒有用的,因爲它需要一些時間來執行。 我可以在這種情況下返回一個元素被發現。 有沒有一個簡單的方法來重構這個,而不必重複fillset的代碼? 我在想是這樣的:
template<bool return_as_soon_as_not_empty>
void fillset(std::set<int>& myset)
{
while(...) {
object[i]->fillset(myset);
if(return_as_soon_as_not_empty && !myset.empty()) {
return;
}
}
if(...)
otherfillset(myset)
}
你怎麼看這件事?歡迎任何其他想法
你可以有一個可選的'maximum'參數來設置要填充的最大對象數量。 –