什么是C++ 11中的lambda表达式?我什么时候用?他们解决了哪些问题在引入之前是不可能的?
一些示例和用例将是有用的.
auto在C++ 14标准中,通用lambda如何工作(关键字作为参数类型)?
它是基于C++模板的,每个不同的参数类型编译器生成一个具有相同主体但替换类型(编译时多态)的新函数,还是更类似于Java的泛型(类型擦除)?
代码示例:
auto glambda = [](auto a) { return a; };
Run Code Online (Sandbox Code Playgroud) 和Lambdas一起玩,我发现了一个我不完全理解的有趣行为.
我有一个struct Overload派生自2个模板参数,并有一个using F1::operator();子句.
现在,如果我从两个函子派生,我只能访问F1的operator()(正如我所料)
如果我从两个Lambda函数派生,则不再适用:我也可以从F2访问operator().
#include <iostream>
// I compiled with g++ (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
//
// g++ -Wall -std=c++11 -g main.cc
// g++ -Wall -std=c++11 -DFUNCTOR -g main.cc
//
// or clang clang version 3.3 (tags/RELEASE_33/rc2)
//
// clang++ -Wall -std=c++11 -g main.cc
// clang++ -Wall -std=c++11 -DFUNCTOR -g main.cc
//
// on a Linux localhost.localdomain 3.9.6-200.fc18.i686 #1 SMP Thu Jun 13
// 19:29:40 UTC 2013 i686 i686 i386 GNU/Linux box …Run Code Online (Sandbox Code Playgroud) 我正在玩一个用C++重载lambdas的技巧.特别:
// For std::function
#include <functional>
// For std::string
#include <string>
// For std::cout
#include <iostream>
template <class... F>
struct overload : F... {
overload(F... f) : F(f)... {}
};
template <class... F>
auto make_overload(F... f) {
return overload<F...>(f...);
}
int main() {
std::function <int(int,int)> f = [](int x,int y) {
return x+y;
};
std::function <double(double,double)> g = [](double x,double y) {
return x+y;
};
std::function <std::string(std::string,std::string)> h = [](std::string x,std::string y) {
return x+y;
};
auto fgh = make_overload(f,g,h); …Run Code Online (Sandbox Code Playgroud) 我试图理解以下来自http://en.cppreference.com/w/cpp/utility/variant/visit的例子.
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
using var_t = std::variant<int, long, double, std::string>;
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// what is this declaration imply???
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::vector<var_t> vec = {10, 15l, 1.5, "hello"};
for (auto& v: vec) {
std::visit(overloaded {
[](auto arg) { std::cout << arg << '\n'; },
[](double arg) { std::cout << std::fixed << arg << '\n'; }, …Run Code Online (Sandbox Code Playgroud) 我有一个基本的lambda,看起来像这样:
auto l = [](){
int i = 0;
cout << i++;
}
Run Code Online (Sandbox Code Playgroud)
多次打电话,将继续打印0.如何保留我?我可以不用仿函数吗?