#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//自动类型 + 匿名函数
void Case1()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
auto fun = [](int n) -> void { cout << n << " "; };
for_each(v.begin(), v.end(), fun);
cout << endl;
}
//自动类型 + 匿名函数 + 匿名函数构造参
void Case2()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
int x = 5;
int y = 6;
auto fun = [x,y](int n) -> void { cout << n << "-" << x << "-" << y <<endl; };
for_each(v.begin(), v.end(), fun);
cout << endl;
}
//自动类型 + 匿名函数 + 匿名函数引用构造参
void Case3()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
int x = 5;
int y = 6;
auto fun = [&x, &y](int n) -> void { cout << n << "-" << x << "-" << y <<endl; x++; y++; };
for_each(v.begin(), v.end(), fun);
cout << endl;
}
//自动类型 + 匿名函数 + 匿名函数引用构造参 + 友元常量对象
class Case4_Class
{
public:
Case4_Class():m_toys(1){}
void text(const vector<int>& v) const
{
for_each(v.begin(), v.end(), [this](int n)
{
cout << this->m_toys << endl;
});
}
private:
int m_toys;
};
void Case4()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
Case4_Class c4;
c4.text(v);
}
//编译器逻辑查验
void Case5()
{
const bool ret = false;
//static_assert(ret, "Case5 requires N < 2.");
}
//类型推算 + 完美转发
class Case6_Class
{
public:
template <typename T, typename U>
auto operator()(T&& t, U&& u) ->decltype( std::forward<T>(t) + std::forward<U>(u))
{
return std::forward<T>(t) + std::forward<U>(u);
}
};
void Case6()
{
cout<< Case6_Class()(1,2)<<endl;;
}
//外部模板
void main()
{
Case6();
system("pause");
}