c++ - C++ 表达式 for_each(v, [](string x) 在语法上是否正确?

标签 c++ 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)>’)
     });

最佳答案

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

  • 如果他们实际上指的是 std::for_each,那么这将是一个打字错误,因为它需要两个迭代器 - 除非他们指的是 future 版本的 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);
    }
    

关于c++ - C++ 表达式 for_each(v, [](string x) 在语法上是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633303/

相关文章:

c++ - 为什么我不能构造一个带有大括号括起来的初始化列表的 gsl::span

c++ - std::atomic 变量的比较操作线程安全吗?

c++ - 从串行窗口解析 json 响应

java - 为什么lambda表达式可以用作比较器?

asp.net-mvc - 使用Linq.Expression使用动态Lambda访问嵌套属性

静态成员变量的 C++ 核心指南

c++ - 基础集路径算法中的错误/错误,我无法弄清楚

c++ - STL 不提供通过索引返回迭代器的函数有什么原因吗?

java - 如何使用 Java 8 streaming api 从 map 列表创建 map map

c++ - gsl::not_null<T*> 与 std::reference_wrapper<T> 与 T&