lambda参数,带有可选的返回值

kyl*_*ewm 6 c++ lambda return-value c++11

我正在尝试编写一个类似的功能std::for_each,除了正常使用外,还可以使用std::function<bool (param)>.错误的返回值意味着我想要摆脱循环.下面的代码是我到目前为止所获得的代码.

a.visit([&](int) -> void)在评估时,第二次调用不会编译!visitor(i).是否有可能使这项工作或我咆哮错误的树?

我正在使用MSVC 2010,但希望代码通常与C++ 11兼容.

#include <list>
#include <string>
#include <iostream>

struct A 
{
    std::list<int> _lst;

    template<typename _F>
    void visit(_F visitor) 
    {
        for(std::list<int>::const_iterator it = _lst.begin(), end = _lst.end() ; it != end ; it++) {
            int i = *it;
            if (std::is_void<decltype(visitor(i))>::value) {
                visitor(i);
            } else {
               if (!visitor(i)) { // <----- error C2171: '!' : illegal on operands of type 'void'
                   break;
               }
            }
        }
    }

};

int main(int argc, char* argv[])
{
    A a;
    // populate a
    for (int i = 0 ; i < 10 ; i++) { 
        a._lst.push_back(i); 
    }

    a.visit([](int i) -> bool {
        std::cout << i << std::endl;
        return i < 5;
    });

    a.visit([](int i) {
        std::cout << i << std::endl;
    });
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*lKO 6

这是我将如何实施for_almost_each; using namespace std出于可读性目的,我加上类型别名.

#include <algorithm>
#include <iterator>
#include <functional>

using namespace std;

template<class Iter, class Func>
Iter
for_almost_each_impl(Iter begin, Iter end, Func func, std::true_type)
{
    for (auto i = begin; i!=end; ++i)
        if (!func(*i))
            return i;
    return end;
}

template<class Iter, class Func>
Iter
for_almost_each_impl(Iter begin, Iter end, Func func, std::false_type)
{
    for_each(begin, end, func);
    return end;
}


template<class Iter, class Func>
Iter for_almost_each(Iter begin, Iter end, Func func)
{
    using Val = typename iterator_traits<Iter>::value_type;
    using Res = typename result_of<Func(Val)>::type;
    return for_almost_each_impl(begin, end,
                                func,
                                is_convertible<Res, bool>{} );
}
Run Code Online (Sandbox Code Playgroud)

我使用过is_convertible,因为它似乎更有意义is_same.