반복되는 패턴이 유형의 가장 약간 더 구체적인 맥락에서 해결되기 때문이 까다 롭습니다. 이 "하나 또는 모든 것"중 하나를 수행하는 것은 일반적으로 읽기 쉽게 작성하기가 어렵습니다. 여기
template <typename IndexedContainer_, typename UnaryOp_>
void apply_for_index(const IndexedContainer_& c, int index, UnaryOp_ op)
{
if (index == -1)
for (auto& elem : c) op(elem);
else
op(c[index]);
}
template <typename ForwardContainer_, typename Iterator_, typename UnaryOp_>
void apply_for_iter(const ForwardContainer_& c, Iterator_ it, UnaryOp_ op)
{
if (it == c.end())
for (auto& elem : c) op(elem);
else
op(*it);
}
:
말했다되고 그건
은 여기 (편의를 위해) 지수 및 사용자 정의 또는 표준 반복자와 함께 귀하의 경우에 작동하는 솔루션입니다 (여기 선명도에 대한 int
으로 인덱스를 harcoded) 당신이 볼 수 있듯이이 수준에서 문제를 해결할 때
int main(int argc, char *argv[])
{
std::vector<int> elems = {0, 1, 2, 3, 4, 5};
printf("All:\n");
bool cond = false;
int four_or_all = cond ? 4 : -1;
apply_for_index(elems, four_or_all, [](int elem) {
printf("elem=%d\n", elem);
});
printf("\nSpecifically 4:\n");
four_or_all = !cond ? 4 : -1;
apply_for_index(elems, four_or_all, [](int elem) {
printf("elem=%d\n", elem);
});
printf("\nAll with iterators:\n");
auto four_or_all_iter = cond ? elems.begin() + 4 : elems.end();
apply_for_iter(elems, four_or_all_iter, [](int elem) {
printf("elem=%d\n", elem);
});
printf("\nSpecifically 4 with iterators:\n");
four_or_all_iter = !cond ? elems.begin() + 4 : elems.end();
apply_for_iter(elems, four_or_all_iter, [](int elem) {
printf("elem=%d\n", elem);
});
return 0;
}
이, 당신이 읽기 어려울 수 있습니다 플래그 또는 감시 값의 어떤 종류를 사용하게 : 몇 가지 예를 사용합니다.
당신은 그걸 자신의 함수로 추출 할 수 없습니까? – user2296177
@ user2296177 : 정확히 무엇을 의미합니까? – goodvibration
첫 번째 코드 블록을 적절한 매개 변수가있는 함수 안에 넣은 다음 해당 패턴을 사용할 때마다 호출하십시오. 당신의'// something 'with something'은 호출 가능한 매개 변수가 될 수 있습니다. – user2296177