C ++表达式for_each(v,[](字符串x)在语法上是否正确?

时间:2017-03-06 18:49:54

标签: c++ c++11 lambda cpp-core-guidelines

以下表达式对for_each()有效吗?

for_each(v,[](string x){
    cout<<x<<endl;
});

参考:CppCoreGuidelines.md#p3-express-intent

上面的表达式抛出错误:

error: no matching function for call to ‘for_each(std::vector<std::__cxx11::basic_string<char> >&,
main()::<lambda(std::__cxx11::string)>)’
     });
      ^
In file included from /usr/include/c++/5/algorithm:62:0,
                 from test.cpp:4:
/usr/include/c++/5/bits/stl_algo.h:3761:5: note: candidate: template<class _IIter, class _Funct> _Funct std::for_each(_IIter,
_IIter, _Funct)
     for_each(_InputIterator __first, _InputIterator __last, _Function __f)
     ^
/usr/include/c++/5/bits/stl_algo.h:3761:5: note:   template argument deduction/substitution failed:
test.cpp:60:6: note:   deduced conflicting types for parameter ‘_IIter’ (‘std::vector<std::__cxx11::basic_string<char> >’ and
‘main()::<lambda(std::__cxx11::string)>’)
     });

1 个答案:

答案 0 :(得分:3)

嗯,核心指南提到for_each,而不是std::for_each。所以很难回答你的问题...

  • 如果它们实际上是指std::for_each,那么它将是一个拼写错误,因为它需要两个迭代器 - 除非它们指的是std::for_each that might be introduced with the Ranges proposals的未来版本。

  • 如果他们指的是通用for_each,那么它可能只是:

    template <typename TContainer, typename TF>
    void for_each(TContainer&& c, TF&& f)
    {
        for(auto&& x : c) f(x);
    }