【发布时间】:2018-12-03 14:15:34
【问题描述】:
我正在尝试使用嵌套的 lambda 捕获构建完美的转发(零复制)构造。 我希望应该有零复制结构,但有些东西坏了。
我从可变参数 arg 移动。打包到元组(移动正常),然后我将元组(移动正常)传递给 std::apply 并在最终嵌套的 lambda 中组装另一个元组(预计移动正常,但 Wrapper CTOR 是复制而不是移动:
#include <iostream>
// tuple printer (ignore it)
template<typename Type, unsigned N, unsigned Last>
struct tuple_printer {
static void print(std::ostream& out, const Type& value) {
out << std::get<N>(value) << ", ";
tuple_printer<Type, N + 1, Last>::print(out, value);
}
};
template<typename Type, unsigned N>
struct tuple_printer<Type, N, N> {
static void print(std::ostream& out, const Type& value) {
out << std::get<N>(value);
}
};
template<typename... Types>
std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& value) {
out << "(";
tuple_printer<std::tuple<Types...>, 0, sizeof...(Types) - 1>::print(out, value);
out << ")";
return out;
}
// THE FUNCTION that returns lambda:
template <class ... Args>
auto f(Args && ... args)
{
// v--- args is a tuple<arg1, arg2, arg3 ...>
return [args_upper = std::make_tuple(std::forward<Args>(args)...)]()
{
// v-- lower "args" is a restored list of arguments - moved from the upper tuple "args"
return std::apply([](auto && ... args) {
// v--- here the Wrapper COPY-CTOR is called instead of moved from
return std::make_tuple(std::forward<decltype(args)>(args)...);
}, std::move(args_upper));
};
}
struct Wrapper {
Wrapper() {
std::cout << "CTOR ";
}
Wrapper(const Wrapper & r) {
std::cout << "COPY-CTOR ";
}
Wrapper(Wrapper&& r) {
std::cout << "MOVE-CTOR ";
}
int w = 42;
friend std::ostream& operator<<(std::ostream& out, const Wrapper& w);
};
std::ostream& operator<<(std::ostream& out, const Wrapper& w) {
out << w.w;
return out;
}
int main() {
auto l = f(1,2.f,"st", Wrapper{});
auto t = l(); // t is tuple
std::cout << t; // tuple printer
// std::cout << l();
}
给出一个输出 CTOR MOVE-CTOR COPY-CTOR (1, 2, st, 42)
【问题讨论】:
-
我认为这里的关键是
decltype(args),这可能会导致引用类型被传递。但是std::forward期望类名通常没有任何引用。你试过decltype(auto)吗? -
@ThomasLang decltype(auto) 仅用于函数返回类型推导。我试过 std::forward<:remove_reference_t>>(args)...);但仍然会发生复制构造
标签: c++ templates lambda variadic-templates perfect-forwarding