How to get C ++ 0x lambda expression expression?

I want to get lambda type as template argument. How to do it?

template<class T> class Foo { public: Foo(T t){ t(); } }; int main() { Foo< type?? > foo([](){ cout<<"construct OK"; }); system("pause"); return 0; } 
+4
source share
2 answers

You can infer the type of a lambda expression when it is an argument to a function of a function of the template of the function whose type is inferred.

Lambda expressions, however, are explicitly forbidden to display inside an unvalued operand --- this includes decltype . It was discovered that this included several unprocessed special cases, and it was found that there was no real opportunity to allow lambda expressions inside decltype and friends. Recall that each lambda expression creates a new unique type.

Instead, you can use std::function<void()> , which can store any function object that can be called without arguments, and returns void as the return type.

 Foo< std::function<void()> > foo([](){ cout<<"construct OK"; }); 

Of course, as I said above, function templates can output their argument type, so you can also make the constructor a template

 class Foo { public: template<typename T> Foo(T t){ t(); } }; Foo foo([](){ cout<<"construct OK"; }); 

But I suppose this is not very useful in your case, since you apparently want to do something with T inside your class definition. For example, saving an object as a non-static data element. With std::function this is possible.

+10
source

There is still an old-fashioned way of using functions for type inference:

 template<class T> class Foo { public: Foo(T t){ t(); } }; template <typename T> Foo<T> make_foo(T const& t) { return Foo<T>(t); } ... make_foo([](){ cout<<"construct OK"; }); 

but I think that compilers that support lambdas usually support decltype and auto , so Matteo's answer is probably better.

+1
source

Source: https://habr.com/ru/post/1340564/


All Articles