通用for_eaches模板

时间:2016-06-18 15:38:43

标签: c++ c++14

在以下程序中,提供了两个模板来执行两个或三个范围内的功能。

#include <algorithm>
#include <iterator>

template <typename R1, typename R2, typename Handler>
void for_eaches(R1 s1,R1 e1,R2 s2,R2 e2,Handler handler)
{
    for (; s1!=e1 && s2!=e2; ++s1,++s2)
        handler(*s1,*s2);
}

template <typename R1, typename R2, typename R3, typename Handler>
void for_eaches(R1 s1,R1 e1,R2 s2,R2 e2, R3 s3, R3 e3, Handler handler)
{
    for (; s1!=e1 && s2!=e2 && s3!=e3; ++s1,++s2,++s3)
        handler(*s1,*s2,*s3);
}

////How could the following be written for the general case?
//template <typename... Iterators, typename Handler>
//void for_eaches(Iterators... iterators,Handler handler)
//{
//  for (; iterator<i>!=iterator<i+1>...; ++iterator<i>...)
//      handler(*iterator...);
//}

int main()
{
    char text[]{"a abc text"};
    char search[]{'a','b','c','d','e'};
    char replace[]{'f','g','h','i','j'};
    int add[]{1,0,2,3,1};

    for (auto s{std::begin(search)},r{std::begin(replace)}; s!=std::end(search) && r!=std::end(replace); ++s,++r)
        std::replace(std::begin(text),std::end(text),*s,*r);

    std::swap(search,replace);

    for_eaches(
        std::begin(search),std::end(search),
        std::begin(replace),std::end(replace),
        [&text](auto& s,auto& r) {std::replace(std::begin(text),std::end(text),s,r); });

    std::swap(search,replace);

    for_eaches(
        std::begin(search),std::end(search),
        std::begin(replace),std::end(replace),
        std::begin(add),std::end(add),
        [&text](auto& s,auto& r, auto&a) 
            {
                auto r_added{r};
                r_added+=a;
                std::replace(std::begin(text),std::end(text),s,r_added); 
            }
    );

    return 0;
}

如何为一般情况编写模板,以便可以提供任意数量的范围?

0 个答案:

没有答案