Is it possible to express lambda expressions/functions using Templates & Exception Handling? [closed]
Shall We can work the Lambda expressions with templates & Exception handling ?
Can any one able to show that in terms of an exapmle program please ?
Is it possible to express lambda expressions/functions using Templates & Exception Handling ?
EDIT: i need an example programs .."Lambda Expression/Functyions using Templates & exception handling "
You can pass a lambda to a template. The simplest example is with std::for_each
:
std::vector<int> v;
for(int i=0;i<10;++i)
{
v.push_back(i);
}
std::for_each(v.begin(),v.end(),[](int& i){i*=2;}); // double each value
std::for_each(v.begin(),v.end(),[](int i){std::cout<<i<<std::endl;}); // print each value
This will thus print
0
2
4
6
8
10
12
14
16
18
You can also throw exceptions from a lambda, and catch them outside. e.g.
try
{
unsigned count=0;
std::for_each(
v.begin(),v.end(),
[&count](int i)
{
if(++count==5)
{
throw i;
}
std::cout<<i<<std::endl;
});
}
catch(int i)
{
std::cout<<"Caught "<<i<<std::endl;
}
With the previous v
, this will then print
0
2
4
6
Caught 8
You can't have a templated lambda, but you can use a lambda within a template:
template<typename T>
void f(std::vector<T> const& v)
{
std::for_each(
v.begin(),v.end(),
[](T const& t){std::cout<<t<<std::endl;}); // print each value
}
You cannot directly template a lambda, but perhaps you can make a templated lambda factory:
#include <functional>
template <typename T>
struct make_adder
{
static inline std::function<T(T,T)> create()
{
return [](T a, T b){ return a + b; };
}
};
Or even:
template <typename T> std::function<T(T,T)> make_adder
{
return [](T a, T b){ return a + b; };
}
Then you can create a couple of instances:
auto int_adder = make_adder<int>::create();
auto black_adder = make_adder<Black>::create();
Not sure if you would need to create lambdas in that way, but if you find you do, then templating can be achieved by such a wrapper.
精彩评论