Perfect forward variadic arguments to lambda
Somehow I need to implement lazy evaluation with c++ variadic lambda. I am not quite sure whether the following code works correctly.
template <typename... ArgsT>
auto lazy_pack(ArgsT&& ... args) {
auto T = [&](bool condition) {
if(condition == false) return;
Foo v(std::forward<ArgsT>(args)...);
v.do_work();
};
return T;
}
The question is, how do I capture a given argument list and perfectly forward them to another templated object? The above example compiles but I am worried about if any dangling reference might happen. Another way is to capture arguments through copy and them and pass to the object:
template <typename... ArgsT>
auto lazy_pack(ArgsT&& ... args) {
auto T = [=](bool condition) {
if(condition == false) return;
Foo v(args...);
v.do_work();
};
return T;
}
I'm not sure I got what you are looking for, but maybe the following code can help you:
#include <tuple>
#include <functional>
#include <cstddef>
#include <utility>
#include <iostream>
struct Foo {
Foo(int v, const char *s): val{v}, str{s} { }
void do_work() { std::cout << val << " " << str << std::endl; }
int val;
const char *str;
};
template<std::size_t... I, typename... ArgsT>
auto lazy_pack(std::index_sequence<I...>, ArgsT&&... args) {
return [tup{std::forward_as_tuple(std::forward<ArgsT>(args)...)}](bool condition) {
if(condition == false) return;
Foo v(std::get<I>(tup)...);
v.do_work();
};
}
template<typename... ArgsT>
auto lazy_pack(ArgsT&& ... args) {
return lazy_pack(std::make_index_sequence<sizeof...(ArgsT)>(), std::forward<ArgsT>(args)...);
}
int main() {
auto l = lazy_pack(42, "bar");
l(false);
l(true);
}
You need at least one more helper function to be able to unpack later the parameters forwarded to the first one.
链接地址: http://www.djcxy.com/p/51580.html上一篇: 如何正确地将C字符串传递给variadic模板函数中的lambda表达式
下一篇: 完美向lambda转发可变参数